import { useEffect } from 'react'
import { useCentralSlotStore } from '../lib/stores/central-slot-store'
import { useSlots } from './prominent-api-hooks'
import { useAllProducts } from './prominent-api-hooks'

export function usePopulateCentralStores() {
  const { data: slotsData } = useSlots()
  const { data: productsData } = useAllProducts()
  const setSlots = useCentralSlotStore((state) => state.setSlots)
  const setProductSlotsMap = useCentralSlotStore((state) => state.setProductSlotsMap)

  useEffect(() => {
    if (slotsData?.slots) {
      // Transform slots to the format expected by the store
      const formattedSlots = slotsData.slots.map((slot: any) => ({
        id: slot.id,
        deliveryDate: slot.deliveryDate,
        deliveryTime: slot.deliveryTime,
        displayDate: slot.displayDate || '',
        displayTime: slot.displayTime || '',
      }))
      setSlots(formattedSlots)

      // Build product slots map
      const productMap: Record<number, any> = {}
      const allProducts = productsData?.products || []

      allProducts.forEach((product: any) => {
        // Find slots that contain this product
        const productSlots = slotsData.slots.filter((slot: any) =>
          slot.products?.some((p: any) => p.id === product.id)
        )

        // Check if flash delivery is available
        const isFlashAvailable = product.isFlashAvailable || false

        // Check if out of stock (no slots available)
        const isOutOfStock = productSlots.length === 0 && !isFlashAvailable

        productMap[product.id] = {
          slotId: productSlots.length > 0 ? productSlots[0].id : null,
          slots: productSlots.map((s: any) => ({
            id: s.id,
            deliveryDate: s.deliveryDate,
            deliveryTime: s.deliveryTime,
            displayDate: s.displayDate || '',
            displayTime: s.displayTime || '',
          })),
          isOutOfStock,
          isFlashAvailable,
        }
      })

      setProductSlotsMap(productMap)
    }
  }, [slotsData, productsData, setSlots, setProductSlotsMap])
}
