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

export default function EditProductGroup() {
  const router = useRouter();
  const { id } = useLocalSearchParams();

  const groupId = parseInt(id as string);

  const { data: groupsData, isLoading } = trpc.admin.product.getGroups.useQuery();
  const groups = groupsData?.groups || [];
  const group = groups.find(g => g.id === groupId);

  if (isLoading) {
    return (
      <AppContainer>
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
          <MyText>Loading group...</MyText>
        </View>
      </AppContainer>
    );
  }

  if (!group) {
    return (
      <AppContainer>
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
          <MyText>Group not found</MyText>
        </View>
      </AppContainer>
    );
  }

  return (
    <AppContainer>
      <ProductGroupForm
        group={group}
        onClose={() => router.back()}
        onSuccess={() => router.back()}
      />
    </AppContainer>
  );
}