"use client";

import { FC, useEffect, useState } from "react";
import useSWR from "swr";
import { TicketList } from "./TicketList";
import { getTicketOverviewCountsQuery } from "app/_graphql/getTicketOverviewCountsQuery";
import { getTicketsByOverviewQuery } from "app/_graphql/getTicketsByOverviewQuery";

type ZammadOverviewProps = {
  name: string;
};

export const ZammadOverview: FC<ZammadOverviewProps> = ({ name }) => {
  const [overviewID, setOverviewID] = useState(null);
  const [tickets, setTickets] = useState([]);
  const [error, setError] = useState(null);

  const { data: overviewData, error: overviewError }: any = useSWR(
    {
      document: getTicketOverviewCountsQuery,
    },
    { refreshInterval: 10000 },
  );
  const { data: ticketData, error: ticketError }: any = useSWR(
    {
      document: getTicketsByOverviewQuery,
      variables: { overviewId: overviewID, pageSize: 250 },
    },
    { refreshInterval: 10000 },
  );
  const overviewLookup = {
    Assigned: "My Assigned Tickets",
    Open: "Open Tickets",
    Urgent: "Escalated Tickets",
    Unassigned: "Unassigned & Open Tickets",
  };

  const findOverviewByName = (name: string) => {
    const fullName = overviewLookup[name];
    return overviewData?.ticketOverviews?.edges?.find(
      (overview: any) => overview.node.name === fullName,
    )?.node?.id;
  };
  useEffect(() => {
    if (overviewData) {
      setOverviewID(findOverviewByName(name));
    }
  }, [overviewData, name]);
  console.log({
    name,
    overviewID,
    overviewData,
    overviewError,
    ticketData,
    ticketError,
  });

  const restFetcher = (url: string) => fetch(url).then((r) => r.json());
  const { data: recent } = useSWR("/api/v1/recent_view", restFetcher);

  const sortTickets = (tickets: any) => {
    return tickets.sort((a: any, b: any) => {
      if (a.internalId < b.internalId) {
        return 1;
      }
      if (a.internalId > b.internalId) {
        return -1;
      }
      return 0;
    });
  };

  useEffect(() => {
    if (name != "Recent") {
      const edges = ticketData?.ticketsByOverview?.edges;
      if (edges) {
        const nodes = edges.map((edge: any) => edge.node);
        console.log({ nodes });
        setError(null);
        setTickets(sortTickets(nodes));
      }

      if (ticketError) {
        setError(ticketError);
      }
    }
  }, [ticketData, ticketError]);

  useEffect(() => {
    const fetchRecentTickets = async () => {
      if (name === "Recent" && recent) {
        let allTickets = [];
        for (const rec of recent) {
          const res = await fetch(`/api/v1/tickets/${rec.o_id}`);
          const tkt = await res.json();
          allTickets.push({
            ...tkt,
            internalId: tkt.id,
            createdAt: tkt.created_at,
            updatedAt: tkt.updated_at,
          });
        }
        setTickets(sortTickets(allTickets));
        console.log({ allTickets });
      }
    };
    fetchRecentTickets();
  }, [name]);

  const shouldRender = tickets && !error;

  return shouldRender && <TicketList title={name} tickets={tickets} />;
};
