import React, { useRef } from 'react';
import { View, Alert } from 'react-native';
import { useLocalSearchParams } from 'expo-router';
import { AppContainer, useManualRefresh, MyText, tw, ImageUploaderNeoItem, ImageUploaderNeoPayload } from 'common-ui';
import ProductForm, { ProductFormRef } from '@/src/components/ProductForm';
import { trpc } from '@/src/trpc-client';
import { useUploadToObjectStorage } from '@/hooks/useUploadToObjectStore';

export default function EditProduct() {
  const { id } = useLocalSearchParams();
  const productId = Number(id);
  const productFormRef = useRef<ProductFormRef>(null);

  const { data: product, isLoading: isFetching, refetch } = trpc.admin.product.getProductById.useQuery(
    { id: productId },
    { enabled: !!productId }
  );
  const { refetch: refetchProducts } = trpc.admin.product.getProducts.useQuery(undefined, {
    enabled: false,
  });

  const updateProduct = trpc.admin.product.updateProduct.useMutation();
  const { upload, isUploading } = useUploadToObjectStorage();

  useManualRefresh(() => refetch());

  const handleSubmit = async (values: any, images: ImageUploaderNeoPayload[], imagesToDelete: string[]) => {
    try {
      // New images have mimeType !== null, existing images have mimeType === null
      const newImages = images.filter(img => img.mimeType !== null);
      let uploadUrls: string[] = [];

      if (newImages.length > 0) {
        const blobs = await Promise.all(
          newImages.map(async (img) => {
            const response = await fetch(img.url);
            const blob = await response.blob();
            return { blob, mimeType: img.mimeType || 'image/jpeg' };
          })
        );

        const result = await upload({ images: blobs, contextString: 'product_info' });
        uploadUrls = result.presignedUrls;
      }

      await updateProduct.mutateAsync({
        id: productId,
        name: values.name,
        shortDescription: values.shortDescription,
        longDescription: values.longDescription,
        unitId: parseInt(values.unitId),
        storeId: parseInt(values.storeId),
        price: parseFloat(values.price),
        marketPrice: values.marketPrice ? parseFloat(values.marketPrice) : undefined,
        incrementStep: 1,
        productQuantity: values.productQuantity || 1,
        isSuspended: values.isSuspended || false,
        isFlashAvailable: values.isFlashAvailable || false,
        flashPrice: values.flashPrice ? parseFloat(values.flashPrice) : null,
        uploadUrls,
        imagesToDelete,
        tagIds: values.tagIds || [],
      });

      await refetch();
      await refetchProducts();
      Alert.alert('Success', 'Product updated successfully!');
      productFormRef.current?.clearImages();
    } catch (error: any) {
      Alert.alert('Error', error.message || 'Failed to update product');
    }
  };

  if (isFetching) {
    return (
      <AppContainer>
        <View style={tw`flex-1 justify-center items-center`}>
          <MyText style={tw`text-gray-600`}>Loading product...</MyText>
        </View>
      </AppContainer>
    );
  }

  if (!product) {
    return (
      <AppContainer>
        <View style={tw`flex-1 justify-center items-center`}>
          <MyText style={tw`text-red-600`}>Product not found</MyText>
        </View>
      </AppContainer>
    );
  }

  const productData = product.product;

  const existingImages: ImageUploaderNeoItem[] = (productData.images || []).map((url) => ({
    imgUrl: url,
    mimeType: null,
  }));
  const existingImageKeys = productData.imageKeys || [];

  const initialValues = {
      name: productData.name,
      shortDescription: productData.shortDescription || '',
      longDescription: productData.longDescription || '',
       unitId: productData.unitId,
       storeId: productData.storeId || 1,
      price: productData.price.toString(),
      marketPrice: productData.marketPrice?.toString() || '',
      deals: productData.deals?.map(deal => ({
        quantity: deal.quantity,
        price: deal.price,
        validTill: deal.validTill ? new Date(deal.validTill) : null,
      })) || [{ quantity: '', price: '', validTill: null }],
       tagIds: productData.tags?.map((tag: any) => tag.id) || [],
       isSuspended: productData.isSuspended || false,
       isFlashAvailable: productData.isFlashAvailable || false,
       flashPrice: productData.flashPrice?.toString() || '',
        productQuantity: productData.productQuantity || 1,
    };

  return (
    <AppContainer>
      <ProductForm
        ref={productFormRef}
        mode="edit"
        initialValues={initialValues}
        onSubmit={handleSubmit}
        isLoading={updateProduct.isPending || isUploading}
        existingImages={existingImages}
        existingImageKeys={existingImageKeys}
      />
    </AppContainer>
  );
}
