"use client";

import { useState } from "react";
import * as XLSX from "xlsx";

export default function ImportPage() {
  const [loading, setLoading] = useState(false);
  const [file, setFile] = useState<File | null>(null);
  const [preview, setPreview] = useState<any[]>([]);
  const [importResults, setImportResults] = useState<{
    success: number;
    failed: number;
    errors: string[];
  } | null>(null);

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = e.target.files?.[0];
    if (!selectedFile) return;

    if (!selectedFile.name.endsWith(".xlsx") && !selectedFile.name.endsWith(".xls")) {
      alert("Please select an Excel file (.xlsx or .xls)");
      return;
    }

    setFile(selectedFile);
    setPreview([]);
    setImportResults(null);

    // Read and preview the file
    const reader = new FileReader();
    reader.onload = (event) => {
      try {
        const data = new Uint8Array(event.target?.result as ArrayBuffer);
        const workbook = XLSX.read(data, { type: "array" });
        const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
        const jsonData = XLSX.utils.sheet_to_json(firstSheet, { raw: false });
        setPreview(jsonData.slice(0, 5)); // Show first 5 rows
      } catch (error) {
        console.error("Error reading file:", error);
        alert("Failed to read Excel file. Please check the file format.");
      }
    };
    reader.readAsArrayBuffer(selectedFile);
  };

  const mapExcelRowToProduct = (row: any): any => {
    // Map Excel columns to product fields
    const product: any = {
      title: row["Product Name"] || row["Title"] || row["Name"] || "",
      sku: row["SKU"] || row["Product ID"] || "",
      bcode1: row["Barcode"] || row["Barcode1"] || "",
      itc1: row["ITC1"] || row["Category Code"] || "",
      itn: row["ITN"] || row["Item Number"] || "",
      scat: row["Category (SCAT)"] || row["SCAT"] || row["Category"] || "",
      cat: row["Category (CAT)"] || row["CAT"] || "",
      itc: row["Category (ITC)"] || row["ITC"] || "",
      shortDescription: row["Short Description"] || row["Description"] || "",
      description: row["Description"] || "",
      fullDescription: row["Full Description"] || "",
      productDetails: row["Product Details"] || "",
      qty: parseFloat(row["Quantity"] || row["Qty"] || "0") || 0,
      stock: parseFloat(row["Stock"] || "0") || 0,
      cost: parseFloat(row["Cost"] || row["QST"] || "0") || 0,
      price: parseFloat(row["Price"] || "0") || 0,
      newCost: parseFloat(row["New Cost"] || row["NEW COST"] || "0") || 0,
      lastSell: parseFloat(row["Last Sell"] || row["LAST SELL"] || "0") || 0,
      vat: parseFloat(row["VAT"] || "0") || 0,
      supplier: row["Supplier"] || "",
      rack: row["Rack"] || "",
      mfg: row["Manufacturer"] || row["Mfg"] || "",
      unit: row["Unit"] || "",
      active: row["Status"]?.toLowerCase() !== "inactive",
      featured: row["Featured"]?.toLowerCase() === "true" || false,
    };

    // Handle images
    const images: string[] = [];
    if (row["Main Image URL"]) images.push(row["Main Image URL"]);
    for (let i = 1; i <= 10; i++) {
      const imgUrl = row[`Image ${i} URL`];
      if (imgUrl) images.push(imgUrl);
    }
    if (images.length > 0) {
      product.images = images;
      product.photoUrl = images[0];
    }

    // Parse product details if it's a JSON string
    if (product.productDetails && typeof product.productDetails === "string") {
      try {
        product.productDetails = JSON.parse(product.productDetails);
      } catch (e) {
        // Keep as string if not valid JSON
      }
    }

    return product;
  };

  const handleImport = async () => {
    if (!file) {
      alert("Please select a file first");
      return;
    }

    setLoading(true);
    setImportResults(null);

    try {
      const reader = new FileReader();
      reader.onload = async (event) => {
        try {
          const data = new Uint8Array(event.target?.result as ArrayBuffer);
          const workbook = XLSX.read(data, { type: "array" });
          const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
          const jsonData = XLSX.utils.sheet_to_json(firstSheet, { raw: false });

          const products = jsonData.map(mapExcelRowToProduct).filter((p) => p.title); // Only products with title

          let success = 0;
          let failed = 0;
          const errors: string[] = [];

          // Import products in batches of 10
          const batchSize = 10;
          for (let i = 0; i < products.length; i += batchSize) {
            const batch = products.slice(i, i + batchSize);
            const results = await Promise.allSettled(
              batch.map(async (product) => {
                try {
                  const response = await fetch("/api/ecommers", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify(product),
                  });

                  if (!response.ok) {
                    const error = await response.json();
                    throw new Error(error.error || "Failed to create product");
                  }

                  return { success: true };
                } catch (error) {
                  throw error;
                }
              })
            );

            results.forEach((result, index) => {
              if (result.status === "fulfilled") {
                success++;
              } else {
                failed++;
                errors.push(
                  `Row ${i + index + 2}: ${products[i + index].title || "Unknown"} - ${result.reason?.message || "Unknown error"}`
                );
              }
            });
          }

          setImportResults({ success, failed, errors });
          alert(`Import completed! ${success} products imported, ${failed} failed.`);
        } catch (error) {
          console.error("Error importing products:", error);
          alert(error instanceof Error ? error.message : "Failed to import products");
        } finally {
          setLoading(false);
        }
      };
      reader.readAsArrayBuffer(file);
    } catch (error) {
      console.error("Error reading file:", error);
      alert("Failed to read file");
      setLoading(false);
    }
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold text-gray-900">Import Products from Excel</h1>
        <p className="text-gray-600 mt-2">Import products from an Excel file (.xlsx or .xls format)</p>
      </div>

      <div className="bg-white rounded-lg shadow p-6 space-y-6">
        <div>
          <label className="block text-sm font-semibold text-gray-700 mb-2">
            Select Excel File
          </label>
          <input
            type="file"
            accept=".xlsx,.xls"
            onChange={handleFileChange}
            className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
          />
          <p className="text-xs text-gray-500 mt-2">
            Supported formats: .xlsx, .xls
          </p>
        </div>

        {preview.length > 0 && (
          <div>
            <h3 className="text-lg font-semibold text-gray-900 mb-3">Preview (First 5 Rows)</h3>
            <div className="overflow-x-auto border border-gray-200 rounded-lg">
              <table className="w-full text-sm">
                <thead className="bg-gray-50">
                  <tr>
                    {Object.keys(preview[0] || {}).map((key) => (
                      <th key={key} className="px-3 py-2 text-left font-semibold text-gray-700 border-b">
                        {key}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {preview.map((row, index) => (
                    <tr key={index} className="border-b">
                      {Object.values(row).map((value: any, cellIndex) => (
                        <td key={cellIndex} className="px-3 py-2 text-gray-600">
                          {String(value || "").substring(0, 50)}
                        </td>
                      ))}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {file && (
          <div className="pt-4 border-t">
            <button
              onClick={handleImport}
              disabled={loading}
              className="w-full md:w-auto px-8 py-3 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg transition disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
            >
              {loading ? (
                <>
                  <svg
                    className="animate-spin h-5 w-5"
                    xmlns="http://www.w3.org/2000/svg"
                    fill="none"
                    viewBox="0 0 24 24"
                  >
                    <circle
                      className="opacity-25"
                      cx="12"
                      cy="12"
                      r="10"
                      stroke="currentColor"
                      strokeWidth="4"
                    ></circle>
                    <path
                      className="opacity-75"
                      fill="currentColor"
                      d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                    ></path>
                  </svg>
                  Importing...
                </>
              ) : (
                <>
                  <svg
                    className="w-5 h-5"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
                    />
                  </svg>
                  Import Products
                </>
              )}
            </button>
          </div>
        )}

        {importResults && (
          <div className={`p-4 rounded-lg ${importResults.failed > 0 ? "bg-yellow-50 border border-yellow-200" : "bg-green-50 border border-green-200"}`}>
            <h3 className="font-semibold mb-2">
              Import Results: {importResults.success} successful, {importResults.failed} failed
            </h3>
            {importResults.errors.length > 0 && (
              <div className="mt-2">
                <p className="text-sm font-semibold mb-1">Errors:</p>
                <ul className="list-disc list-inside text-sm space-y-1">
                  {importResults.errors.slice(0, 10).map((error, index) => (
                    <li key={index} className="text-red-700">{error}</li>
                  ))}
                </ul>
                {importResults.errors.length > 10 && (
                  <p className="text-xs text-gray-600 mt-2">
                    ... and {importResults.errors.length - 10} more errors
                  </p>
                )}
              </div>
            )}
          </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">Import Instructions:</h3>
        <ul className="list-disc list-inside space-y-1 text-blue-800 text-sm">
          <li>Excel file should have column headers matching the export format</li>
          <li>Required columns: Product Name (or Title/Name), SKU (or Product ID)</li>
          <li>Optional columns: All other product fields (Category, Price, Description, etc.)</li>
          <li>Products without a name will be skipped</li>
          <li>Images can be included as "Main Image URL" and "Image 1 URL", "Image 2 URL", etc.</li>
          <li>Status column: "Active" or "Inactive" (default: Active)</li>
          <li>Featured column: "true" or "false" (default: false)</li>
        </ul>
      </div>
    </div>
  );
}

