"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";

type ScrapedData = {
  title?: string;
  price?: string;
  images?: string[];
  shortDescription?: string;
  fullDescription?: string;
  productDetails?: any;
};

export default function ProductScraperPage() {
  const router = useRouter();
  const [url, setUrl] = useState("");
  const [loading, setLoading] = useState(false);
  const [scrapedData, setScrapedData] = useState<ScrapedData | null>(null);
  const [categories, setCategories] = useState<string[]>([]);
  const [loadingCategories, setLoadingCategories] = useState(false);
  
  // Editable form state
  const [formData, setFormData] = useState({
    title: "",
    price: "",
    sku: "",
    shortDescription: "",
    description: "",
    fullDescription: "",
    category: "",
    scat: "",
    images: [] as string[],
    productDetails: "",
    supplier: "",
    qty: "",
    stock: "",
    cost: "",
    newCost: "",
  });

  const [saving, setSaving] = useState(false);
  const [downloadingImages, setDownloadingImages] = useState(false);
  const [newImageUrl, setNewImageUrl] = useState("");
  const [imageDownloadProgress, setImageDownloadProgress] = useState<{ [key: number]: string }>({});

  // Fetch categories from existing products
  useEffect(() => {
    const fetchCategories = async () => {
      setLoadingCategories(true);
      try {
        const [productsRes, ecommersRes] = await Promise.all([
          fetch("/api/products?limit=1000"),
          fetch("/api/ecommers?limit=1000"),
        ]);

        const categorySet = new Set<string>();
        
        if (productsRes.ok) {
          const productsData = await productsRes.json();
          if (Array.isArray(productsData?.products)) {
            productsData.products.forEach((product: any) => {
              const cat = product.scat || product.cat || product.category || product.itc || product.itc1;
              if (cat && cat.trim()) {
                categorySet.add(cat.trim());
              }
            });
          }
        }

        if (ecommersRes.ok) {
          const ecommersData = await ecommersRes.json();
          if (Array.isArray(ecommersData?.products)) {
            ecommersData.products.forEach((product: any) => {
              const cat = product.scat || product.cat || product.category || product.itc || product.itc1;
              if (cat && cat.trim()) {
                categorySet.add(cat.trim());
              }
            });
          }
        }

        setCategories(Array.from(categorySet).sort());
      } catch (error) {
        console.error("Error fetching categories:", error);
      } finally {
        setLoadingCategories(false);
      }
    };

    fetchCategories();
  }, []);

  const handleScrape = async () => {
    if (!url.trim()) {
      alert("Please enter a URL");
      return;
    }

    setLoading(true);
    setScrapedData(null);

    try {
      const response = await fetch("/api/admin/scraper", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ url }),
      });

      const result = await response.json();

      if (!response.ok) {
        // If we have partial data, still show it
        if (result.data) {
          setScrapedData(result.data);
          populateFormData(result.data);
        }
        throw new Error(result.error || result.message || "Failed to scrape product");
      }

      // Handle both success: true and success: false cases
      if (result.success === false && result.data) {
        // Partial data available
        setScrapedData(result.data);
        populateFormData(result.data);
        alert(`Warning: ${result.message || result.error || "Limited information extracted"}. You can still review and edit the product before saving.`);
      } else {
        setScrapedData(result.data);
        populateFormData(result.data);
      }
    } catch (error) {
      console.error("Error scraping product:", error);
      alert(error instanceof Error ? error.message : "Failed to scrape product");
    } finally {
      setLoading(false);
    }
  };

  const populateFormData = (data: ScrapedData) => {
    const priceValue = data.price ? data.price.replace(/[^0-9.]/g, "") : "";
    const productDetailsStr = typeof data.productDetails === "string"
      ? data.productDetails
      : JSON.stringify(data.productDetails || {}, null, 2);

    setFormData({
      title: data.title || "",
      price: priceValue,
      sku: `SCRAPED-${Date.now()}`,
      shortDescription: data.shortDescription || "",
      description: data.shortDescription || "",
      fullDescription: data.fullDescription || "",
      category: "",
      scat: "",
      images: data.images || [],
      productDetails: productDetailsStr,
      supplier: "",
      qty: "",
      stock: "",
      cost: "",
      newCost: "",
    });
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  const handleAddImage = () => {
    if (!newImageUrl.trim()) return;

    // Support multiple URLs separated by commas or newlines
    const urls = newImageUrl
      .split(/[,\n]/)
      .map((url) => url.trim())
      .filter((url) => url && url.startsWith("http"));

    if (urls.length === 0) {
      alert("Please enter a valid image URL");
      return;
    }

    // Add all URLs that aren't already in the list
    const newUrls = urls.filter((url) => !formData.images.includes(url));
    
    if (newUrls.length === 0) {
      alert("All these images are already added");
      return;
    }

    setFormData((prev) => ({
      ...prev,
      images: [...prev.images, ...newUrls],
    }));
    setNewImageUrl("");
    
    if (newUrls.length < urls.length) {
      alert(`Added ${newUrls.length} new images. ${urls.length - newUrls.length} were already in the list.`);
    }
  };

  const handleRemoveImage = (index: number) => {
    setFormData((prev) => ({
      ...prev,
      images: prev.images.filter((_, i) => i !== index),
    }));
  };

  const handleMoveImage = (index: number, direction: "up" | "down") => {
    if (direction === "up" && index > 0) {
      const newImages = [...formData.images];
      [newImages[index - 1], newImages[index]] = [newImages[index], newImages[index - 1]];
      setFormData((prev) => ({ ...prev, images: newImages }));
    } else if (direction === "down" && index < formData.images.length - 1) {
      const newImages = [...formData.images];
      [newImages[index], newImages[index + 1]] = [newImages[index + 1], newImages[index]];
      setFormData((prev) => ({ ...prev, images: newImages }));
    }
  };

  const handleDownloadImages = async () => {
    if (formData.images.length === 0) {
      alert("No images to download");
      return;
    }

    setDownloadingImages(true);
    setImageDownloadProgress({});

    try {
      // Filter out already downloaded images (those starting with /uploads/)
      const externalImages = formData.images.filter((img) => !img.startsWith("/uploads/"));
      
      if (externalImages.length === 0) {
        alert("All images are already downloaded");
        setDownloadingImages(false);
        return;
      }

      // Download images in batches
      const response = await fetch("/api/admin/download-images", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ imageUrls: externalImages }),
      });

      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || "Failed to download images");
      }

      // Create a mapping of original URLs to downloaded URLs
      const urlMapping: { [key: string]: string } = {};
      const failedUrls: string[] = [];
      
      result.results?.forEach((r: any) => {
        if (r.success && r.downloadedUrl) {
          urlMapping[r.url] = r.downloadedUrl;
        } else {
          failedUrls.push(r.url);
        }
      });

      // Replace external URLs with downloaded URLs
      const updatedImages = formData.images.map((img) => {
        if (img.startsWith("/uploads/")) return img; // Already downloaded
        return urlMapping[img] || img; // Use downloaded URL or keep original
      });

      setFormData((prev) => ({ ...prev, images: updatedImages }));

      const successCount = Object.keys(urlMapping).length;
      const failCount = failedUrls.length;

      if (failCount > 0) {
        alert(`Downloaded ${successCount} images successfully. ${failCount} images failed to download.`);
      } else {
        alert(`Successfully downloaded ${successCount} images!`);
      }
    } catch (error) {
      console.error("Error downloading images:", error);
      alert(error instanceof Error ? error.message : "Failed to download images");
    } finally {
      setDownloadingImages(false);
      setImageDownloadProgress({});
    }
  };

  const handleDownloadSingleImage = async (imageUrl: string, index: number) => {
    if (imageUrl.startsWith("/uploads/")) {
      alert("This image is already downloaded");
      return;
    }

    setImageDownloadProgress((prev) => ({ ...prev, [index]: "Downloading..." }));

    try {
      const response = await fetch("/api/admin/download-image", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ imageUrl }),
      });

      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || "Failed to download image");
      }

      // Update the image URL in the array
      const updatedImages = [...formData.images];
      updatedImages[index] = result.url;
      setFormData((prev) => ({ ...prev, images: updatedImages }));

      setImageDownloadProgress((prev) => ({ ...prev, [index]: "Downloaded!" }));
      setTimeout(() => {
        setImageDownloadProgress((prev) => {
          const newProgress = { ...prev };
          delete newProgress[index];
          return newProgress;
        });
      }, 2000);
    } catch (error) {
      console.error("Error downloading image:", error);
      setImageDownloadProgress((prev) => ({ ...prev, [index]: "Failed" }));
      alert(error instanceof Error ? error.message : "Failed to download image");
      setTimeout(() => {
        setImageDownloadProgress((prev) => {
          const newProgress = { ...prev };
          delete newProgress[index];
          return newProgress;
        });
      }, 3000);
    }
  };

  const handleSave = async () => {
    if (!formData.title.trim()) {
      alert("Please enter a product title");
      return;
    }

    setSaving(true);

    try {
      // Parse product details
      let productDetailsParsed: any = {};
      if (formData.productDetails.trim()) {
        try {
          productDetailsParsed = JSON.parse(formData.productDetails);
        } catch (e) {
          // If not valid JSON, store as string
          productDetailsParsed = formData.productDetails;
        }
      }

      const productData = {
        title: formData.title.trim(),
        sku: formData.sku.trim() || `SCRAPED-${Date.now()}`,
        price: parseFloat(formData.price) || 0,
        cost: parseFloat(formData.cost) || 0,
        newCost: parseFloat(formData.newCost) || parseFloat(formData.price) || 0,
        shortDescription: formData.shortDescription.trim(),
        description: formData.description.trim() || formData.shortDescription.trim(),
        fullDescription: formData.fullDescription.trim(),
        productDetails: typeof productDetailsParsed === "string"
          ? productDetailsParsed
          : JSON.stringify(productDetailsParsed),
        images: formData.images,
        photoUrl: formData.images[0] || "",
        scat: formData.scat.trim() || formData.category.trim(),
        category: formData.category.trim() || formData.scat.trim(),
        cat: formData.category.trim() || formData.scat.trim(),
        supplier: formData.supplier.trim(),
        qty: parseFloat(formData.qty) || 0,
        stock: parseFloat(formData.stock) || parseFloat(formData.qty) || 0,
        active: true,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };

      const response = await fetch("/api/ecommers", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(productData),
      });

      const result = await response.json();

      if (!response.ok) {
        // Show detailed error message
        const errorMessage = result.error || result.details || "Failed to save product";
        
        // Check if it's a MongoDB connection error
        if (result.type === "database_error" || errorMessage.includes("MongoDB") || errorMessage.includes("whitelist")) {
          alert(
            `❌ Database Connection Error:\n\n${errorMessage}\n\n` +
            `💡 Solution:\n` +
            `1. Go to MongoDB Atlas → Network Access\n` +
            `2. Add your IP address\n` +
            `3. Wait 1-2 minutes\n` +
            `4. Try again\n\n` +
            `See FIX_MONGODB_CONNECTION.md for detailed instructions.`
          );
        } else {
          alert(`❌ Error: ${errorMessage}`);
        }
        
        throw new Error(errorMessage);
      }

      alert("✅ Product saved successfully!");
      router.push("/admin/products");
    } catch (error) {
      console.error("Error saving product:", error);
      
      // Don't show alert again if we already showed it above
      if (!(error instanceof Error && error.message.includes("Database Connection Error"))) {
        const errorMessage = error instanceof Error ? error.message : "Failed to save product";
        if (!errorMessage.includes("MongoDB") && !errorMessage.includes("whitelist")) {
          alert(`❌ Error: ${errorMessage}`);
        }
      }
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold text-gray-900">Product Scraper</h1>
        <p className="text-gray-600 mt-2">Scrape product information from any website and edit before saving</p>
      </div>

      {/* URL Input */}
      <div className="bg-white rounded-lg shadow p-6">
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              Product URL
            </label>
            <div className="flex gap-4">
              <input
                type="url"
                value={url}
                onChange={(e) => setUrl(e.target.value)}
                placeholder="https://example.com/product"
                className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
              />
              <button
                onClick={handleScrape}
                disabled={loading}
                className="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg transition disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {loading ? "Scraping..." : "Scrape Product"}
              </button>
            </div>
            <p className="text-xs text-gray-500 mt-2">
              Enter the URL of the product page you want to scrape
            </p>
          </div>
        </div>
      </div>

      {/* Product Form */}
      {scrapedData && (
        <div className="bg-white rounded-lg shadow p-6 space-y-6">
          <div className="flex justify-between items-center border-b pb-4">
            <h2 className="text-xl font-semibold text-gray-900">Product Information</h2>
            <button
              onClick={handleSave}
              disabled={saving || !formData.title.trim()}
              className="px-6 py-2 bg-green-600 hover:bg-green-700 text-white font-semibold rounded-lg transition disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {saving ? "Saving..." : "Save to Products"}
            </button>
          </div>

          {/* Basic Information */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-1">
                Title <span className="text-red-500">*</span>
              </label>
              <input
                type="text"
                name="title"
                value={formData.title}
                onChange={handleInputChange}
                placeholder="Product title"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
                required
              />
            </div>

            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-1">
                SKU
              </label>
              <input
                type="text"
                name="sku"
                value={formData.sku}
                onChange={handleInputChange}
                placeholder="Product SKU"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
              />
            </div>

            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-1">
                Price
              </label>
              <input
                type="number"
                name="price"
                value={formData.price}
                onChange={handleInputChange}
                placeholder="0.00"
                step="0.01"
                min="0"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
              />
            </div>

            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-1">
                Cost
              </label>
              <input
                type="number"
                name="cost"
                value={formData.cost}
                onChange={handleInputChange}
                placeholder="0.00"
                step="0.01"
                min="0"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
              />
            </div>

            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-1">
                New Cost
              </label>
              <input
                type="number"
                name="newCost"
                value={formData.newCost}
                onChange={handleInputChange}
                placeholder="0.00"
                step="0.01"
                min="0"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
              />
            </div>

            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-1">
                Category <span className="text-red-500">*</span>
              </label>
              <div className="flex gap-2">
                <select
                  name="scat"
                  value={formData.scat}
                  onChange={handleInputChange}
                  className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
                >
                  <option value="">Select Category</option>
                  {categories.map((cat) => (
                    <option key={cat} value={cat}>
                      {cat}
                    </option>
                  ))}
                </select>
                <input
                  type="text"
                  name="category"
                  value={formData.category}
                  onChange={handleInputChange}
                  placeholder="Or enter new category"
                  className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
                />
              </div>
            </div>

            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-1">
                Supplier
              </label>
              <input
                type="text"
                name="supplier"
                value={formData.supplier}
                onChange={handleInputChange}
                placeholder="Supplier name"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
              />
            </div>

            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-1">
                Quantity / Stock
              </label>
              <div className="flex gap-2">
                <input
                  type="number"
                  name="qty"
                  value={formData.qty}
                  onChange={handleInputChange}
                  placeholder="Quantity"
                  min="0"
                  className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
                />
                <input
                  type="number"
                  name="stock"
                  value={formData.stock}
                  onChange={handleInputChange}
                  placeholder="Stock"
                  min="0"
                  className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
                />
              </div>
            </div>
          </div>

          {/* Descriptions */}
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-1">
                Short Description
              </label>
              <textarea
                name="shortDescription"
                value={formData.shortDescription}
                onChange={handleInputChange}
                rows={2}
                placeholder="Short description for product cards"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
              />
            </div>

            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-1">
                Description
              </label>
              <textarea
                name="description"
                value={formData.description}
                onChange={handleInputChange}
                rows={3}
                placeholder="Product description"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
              />
            </div>

            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-1">
                Full Description
              </label>
              <textarea
                name="fullDescription"
                value={formData.fullDescription}
                onChange={handleInputChange}
                rows={5}
                placeholder="Full detailed description"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
              />
            </div>

            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-1">
                Product Details (JSON format)
              </label>
              <textarea
                name="productDetails"
                value={formData.productDetails}
                onChange={handleInputChange}
                rows={8}
                placeholder='{"key": "value"}'
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 font-mono text-sm"
              />
              <p className="text-xs text-gray-500 mt-1">
                Enter product specifications as JSON object
              </p>
            </div>
          </div>

          {/* Images */}
          <div>
            <div className="flex justify-between items-center mb-2">
              <label className="block text-sm font-semibold text-gray-700">
                Product Images ({formData.images.length})
              </label>
              {formData.images.length > 0 && (
                <button
                  onClick={handleDownloadImages}
                  disabled={downloadingImages}
                  className="px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white font-semibold rounded-lg transition disabled:opacity-50 disabled:cursor-not-allowed text-sm"
                >
                  {downloadingImages ? "Downloading..." : "Download All Images"}
                </button>
              )}
            </div>
            
            {/* Add Image */}
            <div className="flex gap-2 mb-4">
              <input
                type="url"
                value={newImageUrl}
                onChange={(e) => setNewImageUrl(e.target.value)}
                placeholder="Enter image URL (supports multiple URLs separated by commas)"
                className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
                onKeyPress={(e) => {
                  if (e.key === "Enter") {
                    handleAddImage();
                  }
                }}
              />
              <button
                onClick={handleAddImage}
                className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg transition"
              >
                Add Image
              </button>
            </div>
            
            <p className="text-xs text-gray-500 mb-4">
              💡 Tip: You can add multiple image URLs separated by commas, or add them one by one. 
              Click "Download All Images" to save images to your server.
            </p>

            {/* Image Grid */}
            {formData.images.length > 0 && (
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                {formData.images.map((img, index) => {
                  const isDownloaded = img.startsWith("/uploads/");
                  const progress = imageDownloadProgress[index];
                  
                  return (
                    <div key={index} className="relative group">
                      <div className="relative aspect-square rounded-lg overflow-hidden border border-gray-300">
                        <img
                          src={img.startsWith("http") ? img : img.startsWith("/") ? img : `/${img}`}
                          alt={`Product image ${index + 1}`}
                          className="w-full h-full object-cover"
                          onError={(e) => {
                            (e.target as HTMLImageElement).src = "/placeholder-image.png";
                          }}
                        />
                        {index === 0 && (
                          <div className="absolute top-2 left-2 bg-green-500 text-white text-xs px-2 py-1 rounded">
                            Main
                          </div>
                        )}
                        {isDownloaded && (
                          <div className="absolute top-2 right-2 bg-blue-500 text-white text-xs px-2 py-1 rounded">
                            ✓ Downloaded
                          </div>
                        )}
                        {progress && (
                          <div className="absolute inset-0 bg-black bg-opacity-50 flex items-center justify-center">
                            <span className="text-white text-xs">{progress}</span>
                          </div>
                        )}
                      </div>
                      <div className="absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition z-10">
                        {!isDownloaded && !progress && (
                          <button
                            onClick={() => handleDownloadSingleImage(img, index)}
                            className="p-1 bg-purple-500 text-white rounded shadow hover:bg-purple-600"
                            title="Download image"
                          >
                            ⬇
                          </button>
                        )}
                        <button
                          onClick={() => handleMoveImage(index, "up")}
                          disabled={index === 0}
                          className="p-1 bg-white rounded shadow text-gray-700 hover:bg-gray-100 disabled:opacity-50"
                          title="Move up"
                        >
                          ↑
                        </button>
                        <button
                          onClick={() => handleMoveImage(index, "down")}
                          disabled={index === formData.images.length - 1}
                          className="p-1 bg-white rounded shadow text-gray-700 hover:bg-gray-100 disabled:opacity-50"
                          title="Move down"
                        >
                          ↓
                        </button>
                        <button
                          onClick={() => handleRemoveImage(index)}
                          className="p-1 bg-red-500 text-white rounded shadow hover:bg-red-600"
                          title="Remove"
                        >
                          ×
                        </button>
                      </div>
                      <div className="mt-1 text-xs text-gray-500 truncate" title={img}>
                        {isDownloaded ? (
                          "Local: " + img.split("/").pop()
                        ) : (
                          (() => {
                            try {
                              return "External: " + new URL(img).hostname;
                            } catch {
                              return "External: " + img.substring(0, 30) + "...";
                            }
                          })()
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            )}

            {formData.images.length === 0 && (
              <div className="text-center py-8 text-gray-500 border border-dashed border-gray-300 rounded-lg">
                No images added. Add image URLs above.
              </div>
            )}
          </div>

          {/* Save Button */}
          <div className="flex justify-end border-t pt-4">
            <button
              onClick={handleSave}
              disabled={saving || !formData.title.trim()}
              className="px-8 py-3 bg-green-600 hover:bg-green-700 text-white font-semibold rounded-lg transition disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {saving ? "Saving..." : "Save Product"}
            </button>
          </div>
        </div>
      )}

      {/* Instructions */}
      <div className="bg-blue-50 border border-blue-200 rounded-lg p-6">
        <h3 className="font-semibold text-blue-900 mb-2">How to use:</h3>
        <ul className="list-disc list-inside space-y-1 text-blue-800 text-sm">
          <li>Enter the URL of a product page from any e-commerce website</li>
          <li>Click "Scrape Product" to extract product information</li>
          <li>Review and edit all fields (title, price, description, category, images)</li>
          <li>Add or remove images, reorder them (first image is the main image)</li>
          <li>Select or enter a category for the product</li>
          <li>Click "Save Product" to add it to your product catalog</li>
        </ul>
      </div>
    </div>
  );
}
