"use client";

import { useState } from "react";
import * as XLSX from "xlsx";

type ExportOptions = {
  includeImages: boolean;
  includeDetails: boolean;
  sortBy: "title" | "price" | "category" | "createdAt";
  sortOrder: "asc" | "desc";
};

// Excel cell limit is 32,767 characters
const EXCEL_CELL_LIMIT = 32767;

// Helper function to truncate text to Excel's cell limit
const truncateForExcel = (text: string | null | undefined, maxLength: number = EXCEL_CELL_LIMIT): string => {
  if (!text) return "";
  const str = String(text);
  if (str.length <= maxLength) return str;
  return str.substring(0, maxLength - 3) + "..."; // Add "..." to indicate truncation
};

export default function ExportPage() {
  const [loading, setLoading] = useState(false);
  const [options, setOptions] = useState<ExportOptions>({
    includeImages: false,
    includeDetails: true,
    sortBy: "title",
    sortOrder: "asc",
  });

  const handleExport = async () => {
    setLoading(true);

    try {
      // Fetch all products
      const response = await fetch("/api/ecommers?limit=10000");
      if (!response.ok) {
        throw new Error("Failed to fetch products");
      }

      const data = await response.json();
      const products = data.products || [];

      // Sort products
      const sortedProducts = [...products].sort((a, b) => {
        let aVal: any = a[options.sortBy] || "";
        let bVal: any = b[options.sortBy] || "";

        if (options.sortBy === "price") {
          aVal = a.price || 0;
          bVal = b.price || 0;
        } else if (options.sortBy === "createdAt") {
          aVal = new Date(a.createdAt || 0).getTime();
          bVal = new Date(b.createdAt || 0).getTime();
        } else {
          aVal = String(aVal).toLowerCase();
          bVal = String(bVal).toLowerCase();
        }

        if (options.sortOrder === "asc") {
          return aVal > bVal ? 1 : aVal < bVal ? -1 : 0;
        } else {
          return aVal < bVal ? 1 : aVal > bVal ? -1 : 0;
        }
      });

      // Prepare data for Excel
      const excelData = sortedProducts.map((product: any) => {
        // Prepare product details string (might be very long)
        let productDetailsStr = "";
        if (options.includeDetails) {
          if (typeof product.productDetails === "string") {
            productDetailsStr = product.productDetails;
          } else if (product.productDetails) {
            try {
              productDetailsStr = JSON.stringify(product.productDetails);
            } catch (e) {
              productDetailsStr = String(product.productDetails);
            }
          }
        }

        const row: any = {
          "Product ID": truncateForExcel(product._id, 100),
          "Product Name": truncateForExcel(product.title, 500),
          "SKU": truncateForExcel(product.sku, 100),
          "Barcode": truncateForExcel(product.bcode1, 100),
          "ITC1": truncateForExcel(product.itc1, 100),
          "ITN": truncateForExcel(product.itn, 100),
          "Category (SCAT)": truncateForExcel(product.scat, 200),
          "Category (CAT)": truncateForExcel(product.cat, 200),
          "Category (ITC)": truncateForExcel(product.itc, 200),
          "Short Description": truncateForExcel(product.shortDescription, 5000),
          "Description": truncateForExcel(product.description, 10000),
          "Full Description": options.includeDetails ? truncateForExcel(product.fullDescription, EXCEL_CELL_LIMIT) : "",
          "Product Details": truncateForExcel(productDetailsStr, EXCEL_CELL_LIMIT),
          "Quantity": product.qty || 0,
          "Stock": product.stock || 0,
          "Cost": product.cost || 0,
          "Price": product.price || 0,
          "New Cost": product.newCost || 0,
          "Last Sell": product.lastSell || 0,
          "VAT": product.vat || 0,
          "Supplier": truncateForExcel(product.supplier, 200),
          "Rack": truncateForExcel(product.rack, 100),
          "Manufacturer": truncateForExcel(product.mfg, 200),
          "Unit": truncateForExcel(product.unit, 50),
          "Status": product.active !== false ? "Active" : "Inactive",
          "Created At": product.createdAt
            ? new Date(product.createdAt).toLocaleString()
            : "",
          "Updated At": product.updatedAt
            ? new Date(product.updatedAt).toLocaleString()
            : "",
        };

        if (options.includeImages) {
          row["Main Image URL"] = truncateForExcel(product.photoUrl, 500);
          row["Total Images"] = product.images?.length || 0;
          if (product.images && product.images.length > 0) {
            // Limit to first 10 images to avoid too many columns
            const maxImages = Math.min(product.images.length, 10);
            for (let index = 0; index < maxImages; index++) {
              row[`Image ${index + 1} URL`] = truncateForExcel(product.images[index], 500);
            }
          }
        }

        return row;
      });

      // Create workbook
      const wb = XLSX.utils.book_new();
      const ws = XLSX.utils.json_to_sheet(excelData);

      // Set column widths
      const colWidths = [
        { wch: 15 }, // Product ID
        { wch: 30 }, // Product Name
        { wch: 15 }, // SKU
        { wch: 15 }, // Barcode
        { wch: 10 }, // ITC1
        { wch: 10 }, // ITN
        { wch: 20 }, // Category
        { wch: 20 }, // Category CAT
        { wch: 20 }, // Category ITC
        { wch: 30 }, // Short Description
        { wch: 40 }, // Description
        { wch: 50 }, // Full Description
        { wch: 50 }, // Product Details
        { wch: 10 }, // Quantity
        { wch: 10 }, // Stock
        { wch: 10 }, // Cost
        { wch: 10 }, // Price
        { wch: 10 }, // New Cost
        { wch: 10 }, // Last Sell
        { wch: 10 }, // VAT
        { wch: 20 }, // Supplier
        { wch: 10 }, // Rack
        { wch: 20 }, // Manufacturer
        { wch: 10 }, // Unit
        { wch: 10 }, // Status
        { wch: 20 }, // Created At
        { wch: 20 }, // Updated At
      ];

      if (options.includeImages) {
        colWidths.push({ wch: 50 }); // Main Image URL
        colWidths.push({ wch: 10 }); // Total Images
        for (let i = 0; i < 10; i++) {
          colWidths.push({ wch: 50 }); // Image URLs
        }
      }

      ws["!cols"] = colWidths;

      // Add worksheet to workbook
      XLSX.utils.book_append_sheet(wb, ws, "Products");

      // Generate filename
      const filename = `products_export_${new Date().toISOString().split("T")[0]}.xlsx`;

      // Download file
      XLSX.writeFile(wb, filename);

      alert(`Exported ${excelData.length} products to ${filename}`);
    } catch (error) {
      console.error("Error exporting products:", error);
      alert(error instanceof Error ? error.message : "Failed to export products");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold text-gray-900">Export to Excel</h1>
        <p className="text-gray-600 mt-2">Export all products to Excel file (A to Z)</p>
      </div>

      <div className="bg-white rounded-lg shadow p-6 space-y-6">
        <h2 className="text-xl font-semibold text-gray-900">Export Options</h2>

        {/* Sort Options */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              Sort By
            </label>
            <select
              value={options.sortBy}
              onChange={(e) =>
                setOptions({ ...options, sortBy: e.target.value as any })
              }
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
            >
              <option value="title">Product Name (A to Z)</option>
              <option value="price">Price (Low to High)</option>
              <option value="category">Category</option>
              <option value="createdAt">Created Date</option>
            </select>
          </div>

          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              Sort Order
            </label>
            <select
              value={options.sortOrder}
              onChange={(e) =>
                setOptions({ ...options, sortOrder: e.target.value as any })
              }
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
            >
              <option value="asc">Ascending (A to Z)</option>
              <option value="desc">Descending (Z to A)</option>
            </select>
          </div>
        </div>

        {/* Include Options */}
        <div className="space-y-4">
          <label className="flex items-center gap-3">
            <input
              type="checkbox"
              checked={options.includeDetails}
              onChange={(e) =>
                setOptions({ ...options, includeDetails: e.target.checked })
              }
              className="w-5 h-5 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
            />
            <span className="text-sm font-medium text-gray-700">
              Include Full Description and Product Details
            </span>
          </label>

          <label className="flex items-center gap-3">
            <input
              type="checkbox"
              checked={options.includeImages}
              onChange={(e) =>
                setOptions({ ...options, includeImages: e.target.checked })
              }
              className="w-5 h-5 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
            />
            <span className="text-sm font-medium text-gray-700">
              Include Image URLs
            </span>
          </label>
        </div>

        {/* Export Button */}
        <div className="pt-4 border-t">
          <button
            onClick={handleExport}
            disabled={loading}
            className="w-full md:w-auto 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 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>
                Exporting...
              </>
            ) : (
              <>
                <svg
                  className="w-5 h-5"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
                  />
                </svg>
                Export to Excel
              </>
            )}
          </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">Export Information:</h3>
        <ul className="list-disc list-inside space-y-1 text-blue-800 text-sm">
          <li>All products will be exported to an Excel file</li>
          <li>Products are sorted alphabetically by default (A to Z)</li>
          <li>You can choose to include or exclude full descriptions and image URLs</li>
          <li>The file will be downloaded automatically when export is complete</li>
          <li>File format: Excel (.xlsx)</li>
          <li className="text-orange-700 font-semibold">
            Note: Very long text fields (over 32,767 characters) will be automatically truncated to fit Excel's cell limit
          </li>
        </ul>
      </div>
    </div>
  );
}

