import { useState, useEffect, useCallback } from "react";
import axios from "axios";

const useTicketsListener = (userId?: string, canFetch?: boolean) => {
  const [assignedTickets, setAssignedTickets] = useState([]);

  const getData = useCallback(() => {
    axios
      .get("/api/tickets/assignedToUser")
      .then((response) => setAssignedTickets(response.data));
  }, []);

  useEffect(() => {
    if (!canFetch) return;
    getData();
  }, [canFetch, getData]);

  useEffect(() => {
    if (!canFetch) return;
    const intervalId = setInterval(() => {
      getData();
    }, 60 * 1000);

    return () => clearInterval(intervalId);
  }, [assignedTickets, canFetch, getData]);

  if (userId) {
    return {
      assignedTickets,
      totalAssignedTickets: assignedTickets.length,
    };
  }

  return {};
};

export default useTicketsListener;
