import { useState } from "react";
import { apiFetch } from '@/utils/api';
import { toast } from "sonner";
import config from "@/config";
import { Product, ProductImageSortable } from "../types";

type AddImageToProductFn = (productIndex: number, imageUrl: string) => Product[];

const isLikelyWebpUrl = (url: string) => {
  try {
    return new URL(url).pathname.toLowerCase().endsWith(".webp");
  } catch {
    return url.toLowerCase().includes(".webp");
  }
};

interface UseUrlImageUploadProps {
  data: Product[];
  setProductImages: React.Dispatch<React.SetStateAction<ProductImageSortable[]>>;
  addImageToProduct: AddImageToProductFn;
}

export const useUrlImageUpload = ({ 
  data, 
  setProductImages, 
  addImageToProduct 
}: UseUrlImageUploadProps) => {
  const [urlInputs, setUrlInputs] = useState<{ [key: number]: string }>({});
  const [processingUrls, setProcessingUrls] = useState<{ [key: number]: boolean }>({});

  // Handle adding an image from a URL - simplified to skip server
  const handleAddImageFromUrl = async (productIndex: number, url: string) => {
    if (!url || !url.trim()) {
      toast.error("Please enter a valid URL");
      return;
    }
    
    try {
      // Set processing state
      setProcessingUrls(prev => ({ ...prev, [productIndex]: true }));
      
      // Validate URL format
      let validatedUrl = url.trim();
      
      // Add protocol if missing
      if (!validatedUrl.startsWith('http://') && !validatedUrl.startsWith('https://')) {
        validatedUrl = `https://${validatedUrl}`;
      }
      
      // Basic URL validation
      try {
        new URL(validatedUrl);
      } catch (e) {
        toast.error("Invalid URL format. Please enter a valid URL");
        setProcessingUrls(prev => ({ ...prev, [productIndex]: false }));
        return;
      }
      
      let imageUrl = validatedUrl;
      let fileName = "From URL";

      if (isLikelyWebpUrl(validatedUrl)) {
        const response = await apiFetch(`${config.apiUrl}/import/upload-image-url`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            imageUrl: validatedUrl,
            upc: data[productIndex].upc || "",
            supplier_no: data[productIndex].supplier_no || "",
          }),
        });

        if (!response.ok) {
          throw new Error("Failed to convert WebP image URL");
        }

        const result = await response.json();
        if (!result.imageUrl) {
          throw new Error("Upload response did not include an image URL");
        }

        imageUrl = result.imageUrl;
        fileName = result.fileName || "Converted WebP URL";
      }

      // Create a unique ID for this image
      const imageId = `image-${productIndex}-url-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
      
      // Create the new image object with the URL
      const newImage: ProductImageSortable = {
        id: imageId,
        productIndex,
        imageUrl,
        loading: false, // We're not loading from server, so it's ready immediately
        fileName,
        // Add required schema fields
        pid: data[productIndex].id || 0,
        iid: 0,
        type: 0,
        order: 0,
        width: 0,
        height: 0,
        hidden: 0
      };
      
      // Add the image directly to the product images list
      setProductImages(prev => [...prev, newImage]);
      
      // Update the product data with the new image URL
      addImageToProduct(productIndex, imageUrl);
      
      // Clear the URL input field on success
      setUrlInputs(prev => ({ ...prev, [productIndex]: '' }));
      
      toast.success(`Image URL added to ${data[productIndex].name || `Product #${productIndex + 1}`}`);
    } catch (error) {
      console.error('Add image from URL error:', error);
      toast.error(`Failed to add image URL: ${error instanceof Error ? error.message : 'Unknown error'}`);
    } finally {
      setProcessingUrls(prev => ({ ...prev, [productIndex]: false }));
    }
  };

  // Update the URL input value
  const updateUrlInput = (productIndex: number, value: string) => {
    setUrlInputs(prev => ({ ...prev, [productIndex]: value }));
  };

  return {
    urlInputs,
    processingUrls,
    handleAddImageFromUrl,
    updateUrlInput
  };
}; 
