import { Tariff, devlog } from "@frontend/kitui"
import { getTariffById } from "@root/api/tariff"
import {
	addCartTariffs,
	removeMissingCartTariffs,
	setCartTariffStatus,
	useCartStore,
} from "@root/stores/cart"
import { calcCart } from "@root/utils/calcCart/calcCart"
import { useDiscountStore } from "@root/stores/discounts"
import { useTariffStore } from "@root/stores/tariffs"
import { removeTariffFromCart, useUserStore } from "@root/stores/user"
import { useEffect } from "react"


export function useCart() {
	const tariffs = useTariffStore((state) => state.tariffs)
	const cartTariffMap = useCartStore((state) => state.cartTariffMap)
	const cartTariffIds = useUserStore((state) => state.userAccount?.cart)
	const cart = useCartStore((state) => state.cart)
	const discounts = useDiscountStore((state) => state.discounts)
	const purchasesAmount =
        useUserStore((state) => state.userAccount?.wallet.spent) ?? 0
	const isUserNko = useUserStore(state => state.userAccount?.status) === "nko"

	useEffect(() => {
		function addTariffsToCart() {
			const knownTariffs: Tariff[] = []

			cartTariffIds?.forEach(async (tariffId) => {
				if (typeof cartTariffMap[tariffId] === "object") return

				const tariff = tariffs.find((tariff) => tariff._id === tariffId)
				if (tariff) return knownTariffs.push(tariff)

				if (!cartTariffMap[tariffId]) {
					setCartTariffStatus(tariffId, "loading")

					const [tariffByIdResponse, tariffByIdError, tariffByIdStatus] =
                        await getTariffById(tariffId)

					if (tariffByIdError) {
						devlog(tariffByIdError)
						setCartTariffStatus(tariffId, "not found")

						if (tariffByIdStatus === 404) {
							try {
								await removeTariffFromCart(tariffId)

								devlog(
									`Unexistant tariff with id ${tariffId} deleted from cart`
								)
							} catch (error) {
								devlog("Error deleting unexistant tariff from cart", error)
							}
						}

						return
					}

					if (tariffByIdResponse) {
						addCartTariffs([tariffByIdResponse], discounts, purchasesAmount, isUserNko)
					}
				}
			})

			if (knownTariffs.length > 0)
				addCartTariffs(knownTariffs, discounts, purchasesAmount, isUserNko)
		}

		addTariffsToCart()
	}, [cartTariffIds, cartTariffMap, discounts, isUserNko, purchasesAmount, tariffs])

	useEffect(
		function cleanUpCart() {
			if (cartTariffIds)
				removeMissingCartTariffs(cartTariffIds, discounts, purchasesAmount, isUserNko)
		},
		[cartTariffIds, discounts, isUserNko, purchasesAmount]
	)
  const currentTariffs = Object.values(cartTariffMap).filter((tariff): tariff is Tariff => typeof tariff === "object");
	return calcCart(currentTariffs, discounts,purchasesAmount,isUserNko)
}
