import { useEffect, useLayoutEffect, useRef } from "react"
import { Discount, devlog } from "@frontend/kitui"

import { getDiscounts } from "@root/api/price"

export function useDiscounts({
	onNewDiscounts,
	onError,
}: {
  url?: string;
  onNewDiscounts: (response: Discount[]) => void;
  onError: (error: Error) => void;
}) {
	const onNewTariffsRef = useRef(onNewDiscounts)
	const onErrorRef = useRef(onError)

	useLayoutEffect(() => {
		onNewTariffsRef.current = onNewDiscounts
		onErrorRef.current = onError
	}, [onError, onNewDiscounts])

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

		getDiscounts(controller.signal)
			.then(([discounts]) => {
				if (discounts) {
					onNewTariffsRef.current(discounts.Discounts)
				}
			})
			.catch((error) => {
				devlog("Error fetching tariffs", error)
				onErrorRef.current(error)
			})

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