import { CartData, Discount, Tariff } from "@frontend/kitui"
import { calcCart } from "@root/utils/calcCart/calcCart"
import { produce } from "immer"
import { create } from "zustand"
import { devtools } from "zustand/middleware"

interface CartStore {
  cartTariffMap: Record<string, Tariff | "loading" | "not found">;
  cart: CartData;
  isDrawerOpen: boolean;
}

export const useCartStore = create<CartStore>()(
	devtools(
		(get, set) => ({
			cartTariffMap: {},
			cart: {
				services: [],
				priceBeforeDiscounts: 0,
				priceAfterDiscounts: 0,
				itemCount: 0,
				allAppliedDiscounts: [],
				appliedCartPurchasesDiscount: null,
				appliedLoyaltyDiscount: null,
			},
			isDrawerOpen: false,
		}),
		{
			name: "Cart",
			enabled: process.env.NODE_ENV === "development",
			trace: true,
			actionsBlacklist: "rejected",
		}
	)
)

export const setCartTariffStatus = (tariffId: string, status: "loading" | "not found") =>
	useCartStore.setState(
		produce<CartStore>((state) => {
			state.cartTariffMap[tariffId] = status
		}),
		false,
		{
			type: "setCartTariffStatus",
			tariffId,
			status,
		}
	)

export const addCartTariffs = (tariffs: Tariff[], discounts: Discount[], purchasesAmount: number, isUserNko: boolean) =>
	useCartStore.setState(
		produce<CartStore>((state) => {
			tariffs.forEach((tariff) => {
				// if (tariff.isCustom && tariff.privileges[0].serviceKey !== "custom") {
				// 	tariff.privileges[0].serviceKey = "custom"
				// }
		//
				state.cartTariffMap[tariff._id] = tariff
			})
			const cartTariffs = Object.values(state.cartTariffMap).filter(
				(tariff): tariff is Tariff => typeof tariff === "object"
			)
			state.cart = calcCart(cartTariffs, discounts, purchasesAmount, isUserNko)
		}),
		false,
		{
			type: tariffs.length > 0 ? "addCartTariffs" : "rejected",
			tariffs,
		}
	)

export const removeMissingCartTariffs = (tariffIds: string[], discounts: Discount[], purchasesAmount: number, isUserNko: boolean) =>
	useCartStore.setState(
		produce<CartStore>((state) => {
			for (const key in state.cartTariffMap) {
				if (!tariffIds.includes(key)) delete state.cartTariffMap[key]
			}
			const cartTariffs = Object.values(state.cartTariffMap).filter(
				(tariff): tariff is Tariff => typeof tariff === "object"
			)
			state.cart = calcCart(cartTariffs, discounts, purchasesAmount, isUserNko)
		}),
		false,
		{
			type: "rejected",
		}
	)

export const openCartDrawer = () => useCartStore.setState({ isDrawerOpen: true })

export const closeCartDrawer = () => useCartStore.setState({ isDrawerOpen: false })
