import { AssignmentWithCorporateId } from "@/interfaces/results";
import axios from "axios";
import { useEffect, useState } from "react";

export default function useAssignmentsCorporates({
  corporates,
  startDate,
  endDate,
}: {
  corporates: string[];
  startDate: Date | null;
  endDate: Date | null;
}) {
  const [assignments, setAssignments] = useState<AssignmentWithCorporateId[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isError, setIsError] = useState(false);

  const getData = () => {
    if (corporates.length === 0) {
      setAssignments([]);
      return;
    }

    setIsLoading(true);
    const urlSearchParams = new URLSearchParams({
      ids: corporates.join(","),
      ...(startDate ? { startDate: startDate.toISOString() } : {}),
      ...(endDate ? { endDate: endDate.toISOString() } : {}),
    });

    axios
      .get<AssignmentWithCorporateId[]>(
        `/api/assignments/corporate?${urlSearchParams.toString()}`
      )
      .then(async (response) => {
        setAssignments(response.data);
      })
      .finally(() => setIsLoading(false));
  };

  useEffect(getData, [corporates, startDate, endDate]);

  return { assignments, isLoading, isError, reload: getData };
}
