import { useState } from "react";
import { toast } from "sonner";
import { Product, ProductImageSortable } from "../types";

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

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;
      }
      
      // 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: validatedUrl,
        loading: false, // We're not loading from server, so it's ready immediately
        fileName: "From URL",
        // 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, validatedUrl);
      
      // 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
  };
}; 