"use client";

import { FC, useEffect, useState } from "react";
import { redirect } from "next/navigation";
import { getOverviewTicketsAction } from "app/_actions/overviews";

import { TicketList } from "./TicketList";

type ZammadOverviewProps = {
  name: string;
};

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

  if (typeof window !== "undefined") {
    useEffect(() => {
      const hash = window?.location?.hash;

      if (hash) {
        const ticketID = hash.replace("#ticket/zoom/", "");
        if (ticketID && !isNaN(parseInt(ticketID, 10))) {
          redirect(`/tickets/${ticketID}`);
        }
      }
    }, [window?.location?.hash]);
  }

  useEffect(() => {
    const fetchTickets = async () => {
      const { tickets } = await getOverviewTicketsAction(name);
      setTickets(tickets);
    };

    fetchTickets();

    const interval = setInterval(fetchTickets, 10000);

    return () => clearInterval(interval);
  }, [name]);

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