import { View, TouchableOpacity, Alert } from 'react-native';
import { MyText, BottomDropdown, tw, MyFlatList, useMarkDataFetchers } from 'common-ui';
import { useRouter } from 'expo-router';
import dayjs from 'dayjs';
import { useState } from 'react';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { trpc } from '@/src/trpc-client';

export default function ManageOrders() {
  const router = useRouter();
  const [selectedSlotId, setSelectedSlotId] = useState<string | null>(null);
  const { data: slotsData, refetch } = trpc.admin.slots.getAll.useQuery();

  useMarkDataFetchers(() => {
    refetch();
  });

  // Create slot options with Flash Deliveries as first option
  const slotOptions = [
    { label: '⚡ Flash Deliveries', value: 'flash' },
    ...(slotsData?.slots?.map(slot => ({
      label: dayjs(slot.deliveryTime).format('ddd DD MMM, h:mm a'),
      value: slot.id.toString()
    })) || [])
  ];

  const menuItems = [
    {
      title: 'Delivery Sequences',
      icon: 'route',
      color: 'bg-purple-500',
      onPress: () => {
        if (selectedSlotId === 'flash') {
          Alert.alert('Flash Deliveries', 'Flash deliveries do not have delivery sequences. Use the Orders menu to manage flash deliveries.');
          return;
        }
        router.push(`/(drawer)/delivery-sequences?slotId=${selectedSlotId}`);
      },
    },
    {
      title: 'Orders',
      icon: 'list',
      color: 'bg-cyan-500',
      onPress: () => {
        if (selectedSlotId === 'flash') {
          router.push('/(drawer)/orders?filter=flash');
        } else {
          router.push('/(drawer)/orders');
        }
      },
    },
  ];

  return (
    <View style={tw`flex-1`}>
      <MyFlatList
        data={menuItems}
        numColumns={2}
        renderItem={({ item }) => (
          <TouchableOpacity
            style={tw`${item.color} p-6 rounded-2xl shadow-lg mb-4 flex-1`}
            onPress={item.onPress}
          >
            <View style={tw`items-center`}>
              <MaterialIcons name={item.icon as any} size={32} color="white" style={tw`mb-2`} />
              <MyText style={tw`text-white text-lg font-bold text-center`}>
                {item.title}
              </MyText>
            </View>
          </TouchableOpacity>
        )}
        keyExtractor={(item, index) => index.toString()}
        columnWrapperStyle={tw`justify-between gap-4`}
        contentContainerStyle={tw`p-6 gap-4 bg-white flex-1`}
        ListHeaderComponent={
          <>
            <View style={tw`mb-6`}>
              <BottomDropdown
                label='Select Slot'
                options={slotOptions}
                value={selectedSlotId || ''}
                onValueChange={val => setSelectedSlotId(String(val))}
                placeholder="Select Slot"
              />
            </View>
          </>
        }
        
      />
    </View>
  );
}