import { create } from 'zustand';
import { useSlots } from '@/src/hooks/prominent-api-hooks';
import { useEffect } from 'react';
import { SlotsApiType } from "@backend/trpc/router";

type Slot = SlotsApiType['slots'][number];
type ProductAvailability = SlotsApiType['productAvailability'][number];

interface ProductSlotInfo {
  slots: Slot[];
  isOutOfStock: boolean;
  isFlashAvailable: boolean;
}

interface CentralSlotState {
  slots: Slot[];
  productSlotsMap: Record<number, ProductSlotInfo>;
  refetchSlots: (() => Promise<void>) | null;
  setSlotsData: (slots: Slot[], productAvailability: ProductAvailability[]) => void;
  clearSlotsData: () => void;
  setRefetchSlots: (refetch: () => Promise<void>) => void;
}

export const useCentralSlotStore = create<CentralSlotState>((set) => ({
  slots: [],
  productSlotsMap: {},
  refetchSlots: null,
  setSlotsData: (slots, productAvailability) => {
    const productSlotsMap: Record<number, ProductSlotInfo> = {};

    // First, create entries for ALL products from productAvailability
    productAvailability.forEach((product) => {
      productSlotsMap[product.id] = {
        slots: [],
        isOutOfStock: product.isOutOfStock,
        isFlashAvailable: product.isFlashAvailable,
      };
    });

    // Then, populate slots for products that appear in delivery slots
    slots.forEach((slot) => {
      slot.products?.forEach((product) => {
        if (productSlotsMap[product.id]) {
          productSlotsMap[product.id].slots.push(slot);
        }
      });
    });

    set({ slots, productSlotsMap });
  },
  clearSlotsData: () => set({ slots: [], productSlotsMap: {} }),
  setRefetchSlots: (refetchSlots) => set({ refetchSlots }),
}));

export function useInitializeCentralSlotStore() {
  const { data: slotsData, refetch } = useSlots();
  const setSlotsData = useCentralSlotStore((state) => state.setSlotsData);
  const setRefetchSlots = useCentralSlotStore((state) => state.setRefetchSlots);

  useEffect(() => {
    if (slotsData?.slots) {
      setSlotsData(slotsData.slots, slotsData.productAvailability || []);
    }
  }, [slotsData, setSlotsData]);

  useEffect(() => {
    setRefetchSlots(async () => {
      await refetch();
    });
  }, [refetch, setRefetchSlots]);
}
