import React, { useEffect } from 'react';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { FlashDeliveryProducts } from '@/components/SlotSpecificView';
import { useSlotStore } from '@/components/stores/slotStore';
import FlashDeliveryNote from '@/components/FlashDeliveryNote';
import { useFlashNavigationStore } from '@/components/stores/flashNavigationStore';
import { useFocusEffect } from '@react-navigation/native';

export default function FlashDeliveryView() {
  const { storeId } = useLocalSearchParams<{ storeId?: string }>();
  const setStoreId = useSlotStore(state => state.setStoreId);
  const router = useRouter();
  const { shouldNavigateToCart, reset } = useFlashNavigationStore();

  useEffect(() => {
    setStoreId(Number(storeId));
  }, [storeId, setStoreId]);

  useFocusEffect(
    React.useCallback(() => {
      if (shouldNavigateToCart) {
        reset();
        router.push('/(drawer)/(tabs)/flash-delivery/(cart)/cart');
      }
    }, [shouldNavigateToCart, router])
  );

  const handleProductPress = (productId: number) => {
    router.push(`/(drawer)/(tabs)/flash-delivery/product-detail/${productId}`);
  };

  return (
    <>
      <FlashDeliveryNote />
      <FlashDeliveryProducts
        storeId={Number(storeId)}
        baseUrl="/(drawer)/(tabs)/flash-delivery"
        onProductPress={handleProductPress}
      />
    </>
  );
}