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()

		setFetchState("fetching")
		getTariffs(apiPage, tariffsPerPage, controller.signal)
			.then(([result]) => {
				if (result && result.tariffs.length > 0) {
					onSuccessRef.current(result.tariffs)
					setFetchState("idle")
				} else setFetchState("all fetched")
			})
			.catch(([_, error]) => {
				onErrorRef.current?.(error)
			})

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

	return fetchState
}
