import React from 'react';
import { View, Alert } from 'react-native';
import { useRouter, useLocalSearchParams } 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[];
  existingImageUrl?: string;
}

export default function EditTag() {
  const router = useRouter();
  const { tagId } = useLocalSearchParams<{ tagId: string }>();
  const tagIdNum = tagId ? parseInt(tagId) : null;

  const { data: tagData, isLoading: isLoadingTag, error: tagError } = trpc.admin.product.getProductTagById.useQuery(
    { id: tagIdNum || 0 },
    { enabled: !!tagIdNum }
  )
  const { refetch: refetchTags } = trpc.admin.product.getProductTags.useQuery(undefined, {
    enabled: false,
  });
  const updateTag = trpc.admin.product.updateProductTag.useMutation();
  const { data: storesData } = trpc.admin.store.getStores.useQuery();
  const { upload, isUploading } = useUploadToObjectStorage();

  const handleSubmit = async (values: TagFormData, images: ImageUploaderNeoItem[], removedExisting: boolean) => {
    if (!tagIdNum) return;

    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
      } else if (removedExisting) {
        imageUrl = null
      }

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

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

  if (isLoadingTag) {
    return (
      <AppContainer>
        <View style={tw`flex-1 bg-gray-50 justify-center items-center`}>
          <MyText style={tw`text-gray-500`}>Loading tag...</MyText>
        </View>
      </AppContainer>
    );
  }

  if (tagError || !tagData?.tag) {
    return (
      <AppContainer>
        <View style={tw`flex-1 bg-gray-50 justify-center items-center`}>
          <MyText style={tw`text-gray-500`}>Tag not found</MyText>
        </View>
      </AppContainer>
    );
  }

  const tag = tagData.tag;
  const initialValues: TagFormData = {
    tagName: tag.tagName,
    tagDescription: tag.tagDescription || '',
    isDashboardTag: tag.isDashboardTag,
    relatedStores: Array.isArray(tag.relatedStores) ? tag.relatedStores : [],
    existingImageUrl: tag.imageUrl || undefined,
  };

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

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