import { useEffect, useLayoutEffect, useRef, useState } from "react";

import { getTariffs } from "@root/api/tariff";

import type { Tariff } from "@frontend/kitui";

export function useTariffFetcher({
  tariffsPerPage,
  apiPage,
  onSuccess,
  onError,
}: {
  baseUrl?: string;
  tariffsPerPage: number;
  apiPage: number;
  onSuccess: (response: Tariff[]) => void;
  onError?: (error: Error) => void;
}) {
  const [fetchState, setFetchState] = useState<
    "fetching" | "idle" | "all fetched"
  >("idle");
  const onSuccessRef = useRef(onSuccess);
  const onErrorRef = useRef(onError);

  useLayoutEffect(() => {
    onSuccessRef.current = onSuccess;
    onErrorRef.current = onError;
  }, [onError, onSuccess]);

  useEffect(() => {
    const controller = new AbortController();

    const getTariffsRequest = async () => {
      setFetchState("fetching");
      const [tariffs, tariffsError] = await getTariffs(
        apiPage,
        tariffsPerPage,
        controller.signal
      );

      if (tariffsError) {
        return onErrorRef.current?.(new Error(tariffsError));
      }

      if (tariffs && tariffs.tariffs.length > 0) {
        onSuccessRef.current(tariffs.tariffs);
        setFetchState("idle");
      } else setFetchState("all fetched");
    };

    getTariffsRequest();

    return () => controller.abort();
  }, [apiPage, tariffsPerPage]);

  return fetchState;
}
