import { useEffect, useState } from "react";
import useRequest from "./useRequest";
import { GET_CALLER_HISTORY } from "@/core/utils/routes";

const useCallerHistory = (callId, phoneNumber, maxSize) => {
  const requestServer = useRequest();

  const [historyData, setHistoryData] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [hasError, setHasError] = useState(false);

  useEffect(() => {
    const fetchHistory = async () => {
      if (!phoneNumber || !maxSize) return;

      setIsLoading(true);
      setHasError(false);

      try {
        const url = `${GET_CALLER_HISTORY}?phone_number=${phoneNumber}&size=${maxSize}`;
        const { data } = await requestServer(url, "get");
        const items = data?.data || [];

        const filtered = items.filter((item) => item.id !== callId);
        const unique = Array.from(
          new Map(filtered.map((item) => [item.id, item])).values(),
        );

        setHistoryData(unique);
      } catch (error) {
        setHasError(true);
        setHistoryData([]);
      } finally {
        setIsLoading(false);
      }
    };

    fetchHistory();
  }, [callId, phoneNumber, maxSize]);

  return {
    firstItemOfHistory: historyData[0] || false,
    historyList: historyData.length > 1 ? historyData.slice(1) : false,
    isLoadingHistoryList: isLoading,
    errorHistoryList: hasError,
  };
};

export default useCallerHistory;
