import React from 'react';
import { View, Text } from 'react-native';
import { AppContainer } from 'common-ui';
import SlotForm from '../../../components/SlotForm';
import { useRouter, useLocalSearchParams } from 'expo-router';
import { trpc } from '../../../src/trpc-client';

export default function AddSlot() {
  const router = useRouter();
  const { baseslot } = useLocalSearchParams();
  const baseSlotId = baseslot ? parseInt(baseslot as string) : null;
  
  const { refetch } = trpc.admin.slots.getAll.useQuery();
  const { data: baseSlotData, isLoading } = trpc.admin.slots.getSlotById.useQuery(
    { id: baseSlotId! },
    { enabled: !!baseSlotId }
  );

  const handleSlotAdded = () => {
    refetch();
    router.back();
  };

  if (isLoading && baseSlotId) {
    return (
      <AppContainer>
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
          <Text>Loading base slot...</Text>
        </View>
      </AppContainer>
    );
  }

  return (
    <AppContainer>
      <SlotForm 
        onSlotAdded={handleSlotAdded}
        initialProductIds={baseSlotData?.slot?.products?.map(p => p.id) || []}
        initialGroupIds={baseSlotData?.slot?.groupIds || []}
      />
    </AppContainer>
  );
}
