"use client";

import { FC } from "react";
import useSWR from "swr";
import { TicketList } from "./TicketList";
import { getTicketsByOverviewQuery } from "../../../../_graphql/getTicketsByOverviewQuery";

type ZammadOverviewProps = {
  name: string;
  id: string;
};

export const ZammadOverview: FC<ZammadOverviewProps> = ({ name, id }) => {
  const { data: ticketData, error: ticketError }: any = useSWR(
    {
      document: getTicketsByOverviewQuery,
      variables: { overviewId: `gid://zammad/Overview/${id}`, pageSize: 250 },
    },
    { refreshInterval: 10000 },
  );

  const shouldRender = !ticketError && ticketData;
  const tickets =
    ticketData?.ticketsByOverview?.edges.map((edge: any) => edge.node) || [];

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

  return (
    <>
      {shouldRender && <TicketList title={name} tickets={sortedTickets} />}
      {/*ticketError && <div>{ticketError.toString()}</div>*/}
    </>
  );
};
