import React from 'react';
import { Alert } from 'react-native';
import { AppContainer, ImageUploaderNeoPayload } from 'common-ui';
import ProductForm from '@/src/components/ProductForm';
import { trpc } from '@/src/trpc-client';
import { useUploadToObjectStorage } from '@/hooks/useUploadToObjectStore';

export default function AddProduct() {
  const createProduct = trpc.admin.product.createProduct.useMutation();
  const { refetch: refetchProducts } = trpc.admin.product.getProducts.useQuery(undefined, {
    enabled: false,
  });
  const { upload, isUploading } = useUploadToObjectStorage();

  const handleSubmit = async (values: any, images: ImageUploaderNeoPayload[]) => {
    try {
      let uploadUrls: string[] = [];

      if (images.length > 0) {
        const blobs = await Promise.all(
          images.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 createProduct.mutateAsync({
        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) : undefined,
        uploadUrls,
        tagIds: values.tagIds || [],
      });

      await refetchProducts();
      Alert.alert('Success', 'Product created successfully!');
    } catch (error: any) {
      Alert.alert('Error', error.message || 'Failed to create product');
    }
  };

  const initialValues = {
      name: '',
      shortDescription: '',
      longDescription: '',
      unitId: 0,
      price: '',
      storeId: 1,
      marketPrice: '',
       deals: [{ quantity: '', price: '', validTill: new Date() }],
       tagIds: [],
       isSuspended: false,
       isFlashAvailable: false,
       flashPrice: '',
       productQuantity: 1,
    };

  return (
    <AppContainer>
      <ProductForm
        mode="create"
        initialValues={initialValues}
        onSubmit={handleSubmit}
        isLoading={createProduct.isPending || isUploading}
      />
    </AppContainer>
  );
}
