import { trpc } from '@/src/trpc-client';
import dayjs from 'dayjs';

export function useProductSlotIdentifier() {
  // Fetch all slots with products
  const { data: slotsData, isLoading: isProductsLoading } = trpc.user.slots.getSlotsWithProducts.useQuery();
  

  const productSlotsMap = new Map<number, number[]>();

  if (slotsData?.slots) {
    const now = dayjs();

    // Build map of productId to available slot IDs
    slotsData.slots.forEach(slot => {
      if (dayjs(slot.deliveryTime).isAfter(now)) {
        slot.products.forEach(product => {
          if (!productSlotsMap.has(product.id)) {
            productSlotsMap.set(product.id, []);
          }
          productSlotsMap.get(product.id)!.push(slot.id);
        });
      }
    });
  }

  const getQuickestSlot = (productId: number): number | null => {
    
    if (!slotsData?.slots) return null;
    
    const now = dayjs();
    
    // Find slots that contain this product and have future delivery time
    const availableSlots = slotsData.slots.filter(slot =>
      slot.products.some(product => product.id === productId) &&
      dayjs(slot.deliveryTime).isAfter(now)
    );
      // if(productId === 98)
      //   console.log(JSON.stringify(slotsData))
    if (availableSlots.length === 0) return null;

    // Return earliest slot ID (sorted by delivery time)
    const earliestSlot = availableSlots.sort((a, b) =>
      dayjs(a.deliveryTime).diff(dayjs(b.deliveryTime))
    )[0];

    return earliestSlot.id;
  };

  return { getQuickestSlot, productSlotsMap };
}