import React from 'react';
import { View, Alert } from 'react-native';
import { useRouter } from 'expo-router';
import { AppContainer, MyText, tw, type ImageUploaderNeoItem } from 'common-ui';
import TagForm from '@/src/components/TagForm';
import { trpc } from '@/src/trpc-client';
import { useUploadToObjectStorage } from '@/hooks/useUploadToObjectStore';

interface TagFormData {
  tagName: string;
  tagDescription: string;
  isDashboardTag: boolean;
  relatedStores: number[];
}

export default function AddTag() {
  const router = useRouter();
  const createTag = trpc.admin.product.createProductTag.useMutation();
  const { refetch: refetchTags } = trpc.admin.product.getProductTags.useQuery(undefined, {
    enabled: false,
  });
  const { data: storesData } = trpc.admin.store.getStores.useQuery();
  const { upload, isUploading } = useUploadToObjectStorage();

  const handleSubmit = async (values: TagFormData, images: ImageUploaderNeoItem[], _removedExisting: boolean) => {
    try {
      let imageUrl: string | null | undefined;
      let uploadUrls: string[] = []

      const newImage = images.find((image) => image.mimeType !== null)
      if (newImage) {
        const response = await fetch(newImage.imgUrl)
        const blob = await response.blob()
        const result = await upload({
          images: [{ blob, mimeType: newImage.mimeType || 'image/jpeg' }],
          contextString: 'tags',
        })
        imageUrl = result.keys[0]
        uploadUrls = result.presignedUrls
      }

      await createTag.mutateAsync({
        tagName: values.tagName,
        tagDescription: values.tagDescription || undefined,
        imageUrl,
        isDashboardTag: values.isDashboardTag,
        relatedStores: values.relatedStores,
        uploadUrls,
      })

      await refetchTags()
      Alert.alert('Success', 'Tag created successfully', [
        {
          text: 'OK',
          onPress: () => router.back(),
        },
      ])
    } catch (error: any) {
      const errorMessage = error.message || 'Failed to create tag'
      Alert.alert('Error', errorMessage)
    }
  }

  const initialValues: TagFormData = {
    tagName: '',
    tagDescription: '',
    isDashboardTag: false,
    relatedStores: [],
  };

  return (
    <AppContainer>
      <View style={tw`flex-1 bg-gray-50`}>

        {/* Form */}
        <TagForm
          mode="create"
          initialValues={initialValues}
          onSubmit={handleSubmit}
          isLoading={createTag.isPending || isUploading}
          stores={storesData?.stores.map((store: { id: number; name: string }) => ({ id: store.id, name: store.name })) || []}
        />
      </View>
    </AppContainer>
  );
}
