"use client";

import React, { useState, useEffect, useRef } from "react";
import type { WarehouseRecord, ItemRecord, InvoiceExtractedFields } from "@/lib/api";
import { createStockMovementSheet, extractInvoice, getInventorySummary } from "@/lib/api";
import SheetHeaderForm from "./SheetHeaderForm";
import ItemsTable, { createEmptyRow, type SheetRow } from "./ItemsTableNew";
import { generateNextSerialNumber } from "./serialNumberUtils";

/**
 * StockMovementSheetModal Component
 *
 * Main modal container for creating Stock Movement Sheets.
 * Features:
 * - Modal overlay with backdrop
 * - Royal AI invoice extraction
 * - Auto-populated serial number and date
 * - Multi-select warehouse dropdown with dynamic columns
 * - Integration with WarehouseEntryModal
 * - Form validation and submission
 * - Keyboard accessibility (Escape to close)
 */

// Brand colors matching WarehouseEntryModal
const BRAND = "#4c6fff";
const BRAND_GRADIENT = "linear-gradient(135deg, #4c6fff 0%, #5b7cff 100%)";
const BRAND_SHADOW = "0 4px 12px rgba(76, 111, 255, 0.35)";

interface StockMovementSheetModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
  warehouses: WarehouseRecord[];
  items: ItemRecord[];
}

export default function StockMovementSheetModal({
  isOpen,
  onClose,
  onSuccess,
  warehouses,
  items,
}: StockMovementSheetModalProps) {
  // Serial number and date
  const [serialNumber, setSerialNumber] = useState<string>("SMS-00001");
  const [entryDate, setEntryDate] = useState<string>("");
  
  // Warehouse selection
  const [selectedWarehouses, setSelectedWarehouses] = useState<string[]>([]);
  
  // Row data
  const [rows, setRows] = useState<SheetRow[]>([]);
  
  // Royal AI extraction
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [extracting, setExtracting] = useState(false);
  const [extracted, setExtracted] = useState<InvoiceExtractedFields | null>(null);
  const [showExtractionPreview, setShowExtractionPreview] = useState(false);
  
  // Submission state
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [toast, setToast] = useState<string | null>(null);
  const [showConfirmDialog, setShowConfirmDialog] = useState(false);
  
  // Inventory summary for calculations
  const [currentTotalMt, setCurrentTotalMt] = useState<number>(0);
  const [hasReachedThreshold, setHasReachedThreshold] = useState<boolean>(false);
  const THRESHOLD = 26000;

  // Initialize modal when opened
  useEffect(() => {
    if (isOpen) {
      initializeModal();
    }
  }, [isOpen]); // eslint-disable-line react-hooks/exhaustive-deps

  async function initializeModal() {
    // Generate serial number
    try {
      const nextSerial = await generateNextSerialNumber();
      setSerialNumber(nextSerial);
    } catch (error) {
      console.error("Error generating serial number:", error);
      setSerialNumber("SMS-00001");
    }
    
    // Set current date
    const today = new Date().toISOString().split("T")[0];
    setEntryDate(today);
    
    // Initialize with empty rows
    setRows([]);
    
    // Fetch current inventory total
    try {
      const summary = await getInventorySummary();
      setCurrentTotalMt(summary.totalAvailableMt);
      setHasReachedThreshold(summary.hasReachedThreshold);
    } catch (error) {
      console.error("Error fetching inventory summary:", error);
    }
    
    // Reset state
    setSelectedWarehouses([]);
    setExtracted(null);
    setShowExtractionPreview(false);
    setError(null);
    setToast(null);
    setShowConfirmDialog(false);
  }

  // Handle warehouse selection change
  function handleWarehouseChange(newWarehouses: string[]) {
    setSelectedWarehouses(newWarehouses);
    
    // Update all rows to distribute quantities to new warehouse selection
    setRows(prev => prev.map(row => {
      if (row.quantity) {
        const warehouseBags: Record<string, string> = {};
        newWarehouses.forEach(wId => {
          warehouseBags[wId] = row.quantity;
        });
        return { ...row, warehouseBags };
      }
      return row;
    }));
  }

  // Handle row updates
  function handleRowUpdate(rowId: string, updates: Partial<SheetRow>) {
    setRows(prev => prev.map(r => r.id === rowId ? { ...r, ...updates } : r));
  }

  // Add new row
  function handleAddRow() {
    setRows(prev => [...prev, createEmptyRow()]);
  }

  // Remove row
  function handleRemoveRow(rowId: string) {
    setRows(prev => prev.filter(r => r.id !== rowId));
  }

  function calculateDraftTotalMt(draftRows = rows) {
    return draftRows.reduce((sum, row) => {
      const totalBags = Number(row.quantity) || 0;
      const bagWeightKg = row.bagWeightKg || 0;
      const totalMtOverride = row.totalMtOverride !== "" ? Number(row.totalMtOverride) : null;

      if (totalMtOverride !== null) return sum + totalMtOverride;
      if (bagWeightKg > 0) return sum + (totalBags * bagWeightKg) / 1000;
      return sum;
    }, 0);
  }

  // Royal AI extraction
  async function handleFileUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    
    setExtracting(true);
    setError(null);
    
    try {
      const result = await extractInvoice(file);
      const fields = result.extracted_fields ?? (result as unknown as InvoiceExtractedFields);
      setExtracted(fields);
      setShowExtractionPreview(true);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Extraction failed.");
    } finally {
      setExtracting(false);
      if (fileInputRef.current) fileInputRef.current.value = "";
    }
  }

  function applyExtraction() {
    setShowExtractionPreview(false);
  }

  // Form submission
  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    
    // Show confirmation dialog instead of submitting directly
    setShowConfirmDialog(true);
  }

  // Actual submission after confirmation
  async function confirmSubmit() {
    setShowConfirmDialog(false);
    
    // Validation
    const activeRows = rows.filter(r => {
      const totalBags = Number(r.quantity) || 0;
      return r.itemId && totalBags > 0;
    });
    
    if (activeRows.length === 0) {
      setError("Add at least one item with quantities before submitting.");
      return;
    }
    
    // Calculate total MT being added in this sheet
    const totalMtBeingAdded = calculateDraftTotalMt(activeRows);
    
    // Calculate what the new total will be after this stock-in
    const newTotalMt = currentTotalMt + totalMtBeingAdded;
    
    // Temporarily disabled: keep the Royal AI REQUIRED indicator visible, but do not block submission.
    // if (!hasReachedThreshold && newTotalMt < THRESHOLD && !extracted) {
    //   setError(
    //     `Invoice upload is required.\n\n` +
    //     `Current inventory: ${currentTotalMt.toFixed(2)} MT\n` +
    //     `Adding: ${totalMtBeingAdded.toFixed(2)} MT\n` +
    //     `New total: ${newTotalMt.toFixed(2)} MT\n\n` +
    //     `Invoice upload is mandatory until inventory first reaches ${THRESHOLD.toLocaleString()} MT.`
    //   );
    //   return;
    // }
    
    // Validate required fields: batch number and expiry date
    const missingFields: string[] = [];
    activeRows.forEach((row, idx) => {
      const rowNum = idx + 1;
      if (!row.batchNumber || row.batchNumber.trim() === "") {
        missingFields.push(`Row ${rowNum}: Batch Number is required`);
      }
      if (!row.expiryDate || row.expiryDate.trim() === "") {
        missingFields.push(`Row ${rowNum}: Expiry Date is required`);
      }
    });
    
    if (missingFields.length > 0) {
      setError(`Please fill in all required fields:\n${missingFields.join("\n")}`);
      return;
    }
    
    // Check for duplicate item codes
    const itemCodes = activeRows.map(r => r.itemCode);
    const seen = new Set<string>();
    const duplicates: string[] = [];
    itemCodes.forEach(code => {
      if (seen.has(code)) {
        if (!duplicates.includes(code)) duplicates.push(code);
      }
      seen.add(code);
    });
    
    if (duplicates.length > 0) {
      setError(`Warning: Duplicate item codes found: ${duplicates.join(", ")}. This is allowed for different batches.`);
      // Don't return - allow submission with duplicates
    }
    
    setSubmitting(true);
    setError(null);
    
    try {
      const lineItems = activeRows.map(r => {
        const bags: Record<string, number> = {};
        Object.entries(r.warehouseBags).forEach(([wId, v]) => {
          const n = Number(v);
          if (n > 0) bags[wId] = n;
        });
        
        const totalMtOverride = r.totalMtOverride !== ""
          ? (Number(r.totalMtOverride) || null)
          : null;
        
        return {
          itemId: r.itemId,
          batchNumber: r.batchNumber.trim() || "—",
          expiryDate: r.expiryDate || "2099-12-31",
          warehouseBags: bags,
          totalMtOverride,
        };
      });
      
      // Build invoice payload if extracted
      const invoicePayload = extracted ? {
        documentNumber: extracted.document_number,
        documentDate: extracted.document_date,
        referenceNumber: extracted.reference_number,
        warehouseName: extracted.warehouse_name,
        itemCode: extracted.item_code,
        itemName: extracted.item_name,
        batchNumber: extracted.batch_number,
        allBatches: extracted.all_batches,
        expiryDate: extracted.expiry_date,
        quantityMt: extracted.quantity_mt,
        unit: extracted.unit,
        unitPrice: extracted.unit_price,
        supplierName: extracted.supplier_name,
        supplierTrn: extracted.supplier_trn,
        buyerName: extracted.buyer_name,
        buyerTrn: extracted.buyer_trn,
        totalAmount: extracted.total_amount,
        vatAmount: extracted.vat_amount,
        netAmount: extracted.net_amount,
        currency: extracted.currency,
        paymentTerms: extracted.payment_terms,
        dueDate: extracted.due_date,
      } : undefined;
      
      await createStockMovementSheet({
        documentNumber: serialNumber,
        documentDate: entryDate,
        lineItems,
        invoice: invoicePayload,
      });
      
      // Success - close modal and refresh
      handleClose();
      onSuccess();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Submission failed.");
    } finally {
      setSubmitting(false);
    }
  }

  // Handle modal close
  function handleClose() {
    onClose();
  }

  // Handle Escape key
  useEffect(() => {
    function handleEscape(e: KeyboardEvent) {
      if (e.key === "Escape" && isOpen && !showExtractionPreview) {
        handleClose();
      }
    }
    
    document.addEventListener("keydown", handleEscape);
    return () => document.removeEventListener("keydown", handleEscape);
  }, [isOpen, showExtractionPreview]); // eslint-disable-line react-hooks/exhaustive-deps

  // Auto-dismiss toast after 5 seconds
  useEffect(() => {
    if (toast) {
      const timer = setTimeout(() => setToast(null), 5000);
      return () => clearTimeout(timer);
    }
  }, [toast]);

  if (!isOpen) return null;

  const draftTotalMt = calculateDraftTotalMt();
  const projectedTotalMt = currentTotalMt + draftTotalMt;
  const invoiceRequiredForDraft = !hasReachedThreshold && projectedTotalMt < THRESHOLD;

  return (
    <>
      {/* Modal Backdrop */}
      <div
        style={{
          position: "fixed",
          inset: 0,
          zIndex: 1000,
          background: "rgba(0,0,0,0.6)",
          backdropFilter: "blur(4px)",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          padding: "20px",
        }}
        onClick={handleClose}
      >
        {/* Modal Container */}
        <div
          style={{
            background: "#fff",
            borderRadius: 16,
            maxWidth: "95vw",
            width: "100%",
            maxHeight: "90vh",
            border: "1.5px solid rgba(76, 111, 255, 0.25)",
            boxShadow: "0 24px 64px rgba(15,22,48,0.22), 0 0 0 1px rgba(76,111,255,0.08)",
            display: "flex",
            flexDirection: "column",
            overflow: "hidden",
          }}
          onClick={(e) => e.stopPropagation()}
        >
          {/* Modal Header */}
          <div
            style={{
              padding: "22px 26px",
              borderBottom: "1px solid rgba(0,0,0,0.07)",
              background: BRAND_GRADIENT,
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
            }}
          >
            <div>
              <h2
                style={{
                  margin: 0,
                  fontSize: "1.2rem",
                  fontWeight: 700,
                  color: "#fff",
                  letterSpacing: "-0.02em",
                }}
              >
                Stock-In Process
              </h2>
              <p
                style={{
                  margin: "4px 0 0",
                  fontSize: "0.84rem",
                  color: "rgba(255,255,255,0.82)",
                }}
              >
                Upload invoice with Royal AI or enter manually
              </p>
            </div>
            <button
              type="button"
              onClick={handleClose}
              style={{
                background: "rgba(255,255,255,0.15)",
                border: "none",
                color: "#fff",
                borderRadius: 8,
                padding: "8px 12px",
                cursor: "pointer",
                fontSize: "1.2rem",
                lineHeight: 1,
              }}
            >
              ✕
            </button>
          </div>

          {/* Modal Body */}
          <div style={{ flex: 1, overflowY: "auto", padding: "24px 26px" }}>
            <form onSubmit={handleSubmit} id="sheet-form">
              {/* Toast Message */}
              {toast && (
                <div
                  style={{
                    position: "fixed",
                    top: 20,
                    right: 20,
                    zIndex: 2000,
                    padding: "12px 16px",
                    borderRadius: 8,
                    background: "#fff5f5",
                    border: "1px solid rgba(214,69,69,0.3)",
                    color: "#d64545",
                    fontSize: "0.88rem",
                    display: "flex",
                    alignItems: "center",
                    gap: 10,
                    boxShadow: "0 4px 12px rgba(0,0,0,0.15)",
                    minWidth: 300,
                    maxWidth: 500,
                  }}
                >
                  <span style={{ fontSize: "1.2rem" }}>⚠</span>
                  <span style={{ flex: 1 }}>{toast}</span>
                  <button
                    type="button"
                    onClick={() => setToast(null)}
                    style={{
                      background: "none",
                      border: "none",
                      color: "#d64545",
                      cursor: "pointer",
                      fontSize: "1.1rem",
                    }}
                  >
                    ✕
                  </button>
                </div>
              )}

              {/* Error Message */}
              {error && (
                <div
                  style={{
                    marginBottom: 18,
                    padding: "12px 16px",
                    borderRadius: 8,
                    background: "#fff5f5",
                    border: "1px solid rgba(214,69,69,0.3)",
                    color: "#d64545",
                    fontSize: "0.88rem",
                    display: "flex",
                    alignItems: "flex-start",
                    gap: 10,
                  }}
                >
                  <span style={{ fontSize: "1.2rem", marginTop: "2px" }}>⚠</span>
                  <span style={{ flex: 1, whiteSpace: "pre-line" }}>{error}</span>
                  <button
                    type="button"
                    onClick={() => setError(null)}
                    style={{
                      background: "none",
                      border: "none",
                      color: "#d64545",
                      cursor: "pointer",
                      fontSize: "1.1rem",
                      marginTop: "2px",
                    }}
                  >
                    ✕
                  </button>
                </div>
              )}

              {/* Royal AI Upload Section */}
              <div
                style={{
                  marginBottom: 20,
                  background: "#0a0e1a",
                  borderRadius: 14,
                  padding: "22px 28px",
                  display: "flex",
                  alignItems: "center",
                  gap: 20,
                }}
              >
                <div style={{ flex: 1 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}>
                    <span style={{ fontSize: "1.4rem", color: "#fff" }}>✦</span>
                    <h3
                      style={{
                        margin: 0,
                        fontSize: "1.1rem",
                        fontWeight: 800,
                        color: "#fff",
                        letterSpacing: "-0.01em",
                      }}
                    >
                      Royal AI Extraction
                      {invoiceRequiredForDraft && (
                        <span style={{ 
                          marginLeft: 8, 
                          fontSize: "0.75rem", 
                          color: "#ff6b6b",
                          fontWeight: 600,
                          background: "rgba(255,107,107,0.15)",
                          padding: "2px 8px",
                          borderRadius: 4,
                        }}>
                          REQUIRED
                        </span>
                      )}
                      {!invoiceRequiredForDraft && (
                        <span style={{ 
                          marginLeft: 8, 
                          fontSize: "0.75rem", 
                          color: "rgba(255,255,255,0.5)",
                          fontWeight: 600,
                        }}>
                          (Optional)
                        </span>
                      )}
                    </h3>
                  </div>
                  <p
                    style={{
                      margin: 0,
                      fontSize: "0.86rem",
                      color: "rgba(255,255,255,0.6)",
                      lineHeight: 1.5,
                    }}
                  >
                    Upload a tax invoice PDF and Royal AI will automatically extract item codes, batch numbers, quantities and more.
                    {invoiceRequiredForDraft && (
                      <span style={{ display: "block", marginTop: 4, color: "#ff6b6b", fontSize: "0.82rem" }}>
                        Invoice required until inventory first reaches {THRESHOLD.toLocaleString()} MT (Projected: {projectedTotalMt.toFixed(2)} MT)
                      </span>
                    )}
                    {!invoiceRequiredForDraft && hasReachedThreshold && (
                      <span style={{ display: "block", marginTop: 4, color: "rgba(255,255,255,0.55)", fontSize: "0.82rem" }}>
                        Threshold was already reached before, so invoice upload is optional.
                      </span>
                    )}
                  </p>
                </div>
                <div style={{ flexShrink: 0 }}>
                  <input
                    ref={fileInputRef}
                    type="file"
                    accept=".pdf,.png,.jpg,.jpeg"
                    style={{ display: "none" }}
                    onChange={handleFileUpload}
                  />
                  <button
                    type="button"
                    disabled={extracting}
                    onClick={() => fileInputRef.current?.click()}
                    style={{
                      background: "#fff",
                      color: "#0a0e1a",
                      border: "none",
                      borderRadius: 8,
                      padding: "11px 22px",
                      fontSize: "0.88rem",
                      fontWeight: 700,
                      cursor: extracting ? "not-allowed" : "pointer",
                      whiteSpace: "nowrap",
                      opacity: extracting ? 0.6 : 1,
                    }}
                  >
                    📄 {extracting ? "Uploading..." : "Upload Invoice"}
                  </button>
                </div>
              </div>

              {/* Sheet Header Form - Now at top */}
              <SheetHeaderForm
                serialNumber={serialNumber}
                entryDate={entryDate}
                onDateChange={setEntryDate}
                selectedWarehouses={selectedWarehouses}
                onWarehousesChange={handleWarehouseChange}
                warehouses={warehouses}
              />

              {/* Summary Cards - Now scrollable */}
              <div
                style={{
                  marginBottom: 18,
                  background: "var(--brand-soft)",
                  border: "1px solid rgba(59,91,219,0.18)",
                  borderRadius: 10,
                  padding: "12px 16px",
                }}
              >
                <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10 }}>
                  <SummaryCardSmall label="In Stock" value={formatNumber(currentTotalMt)} unit="MT" />
                  <SummaryCardSmall 
                    label="This Sheet" 
                    value={formatNumber(rows.reduce((s, r) => s + (Number(r.quantity) || 0) * ((r.bagWeightKg || 0) / 1000), 0))} 
                    unit="MT" 
                    subUnit={`${formatNumber(rows.reduce((s, r) => s + (Number(r.quantity) || 0), 0))} bags`}
                    highlight 
                  />
                  <SummaryCardSmall 
                    label="After Submit" 
                    value={formatNumber(currentTotalMt + rows.reduce((s, r) => s + (Number(r.quantity) || 0) * ((r.bagWeightKg || 0) / 1000), 0))} 
                    unit="MT" 
                  />
                  <SummaryCardSmall
                    label="Total Empty"
                    value={formatNumber(Math.max(0, THRESHOLD - currentTotalMt - rows.reduce((s, r) => s + (Number(r.quantity) || 0) * ((r.bagWeightKg || 0) / 1000), 0)))}
                    unit="MT"
                    danger={Math.max(0, THRESHOLD - currentTotalMt - rows.reduce((s, r) => s + (Number(r.quantity) || 0) * ((r.bagWeightKg || 0) / 1000), 0)) < 500}
                  />
                </div>
              </div>

              {/* Items Table */}
              <ItemsTable
                rows={rows}
                selectedWarehouses={selectedWarehouses}
                warehouses={warehouses}
                items={items}
                onRowUpdate={handleRowUpdate}
                onAddRow={handleAddRow}
                onRemoveRow={handleRemoveRow}
                currentTotalMt={currentTotalMt}
                threshold={THRESHOLD}
                onError={setToast}
              />
            </form>
          </div>

          {/* Modal Footer */}
          <div
            style={{
              padding: "16px 26px",
              borderTop: "1px solid rgba(0,0,0,0.07)",
              background: "#f8f9fb",
              display: "flex",
              gap: 10,
              justifyContent: "flex-end",
            }}
          >
            <button
              type="button"
              onClick={handleClose}
              style={{
                padding: "10px 22px",
                borderRadius: 8,
                border: "1.5px solid rgba(0,0,0,0.12)",
                background: "#fff",
                color: "#495057",
                fontSize: "0.88rem",
                fontWeight: 600,
                cursor: "pointer",
              }}
            >
              Cancel
            </button>
            <button
              type="submit"
              form="sheet-form"
              disabled={submitting}
              style={{
                padding: "10px 22px",
                borderRadius: 8,
                border: "none",
                background: submitting ? "#adb5bd" : BRAND_GRADIENT,
                color: "#fff",
                fontSize: "0.88rem",
                fontWeight: 600,
                cursor: submitting ? "not-allowed" : "pointer",
                boxShadow: submitting ? "none" : BRAND_SHADOW,
                display: "flex",
                alignItems: "center",
                gap: 8,
              }}
            >
              {submitting ? (
                <>
                  <span
                    style={{
                      display: "inline-block",
                      width: 14,
                      height: 14,
                      border: "2px solid rgba(255,255,255,0.3)",
                      borderTopColor: "#fff",
                      borderRadius: "50%",
                      animation: "spin 0.8s linear infinite",
                    }}
                  />
                  Submitting...
                </>
              ) : (
                <>
                  <svg
                    width="15"
                    height="15"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2.5"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  >
                    <polyline points="20 6 9 17 4 12" />
                  </svg>
                  Submit for Approval
                </>
              )}
            </button>
          </div>
        </div>
      </div>

      {/* Royal AI Loading Modal */}
      {extracting && (
        <div
          style={{
            position: "fixed",
            inset: 0,
            zIndex: 1100,
            background: "rgba(0,0,0,0.75)",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <div
            style={{
              background: "#0a0e1a",
              borderRadius: 20,
              overflow: "hidden",
              width: 480,
              maxWidth: "90vw",
            }}
          >
            <video
              autoPlay
              loop
              muted
              playsInline
              style={{
                width: "100%",
                display: "block",
                maxHeight: 260,
                objectFit: "cover",
                opacity: 0.7,
              }}
            >
              <source src="/royalai.mp4" type="video/mp4" />
            </video>
            <div style={{ padding: "24px 28px", textAlign: "center" }}>
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  gap: 10,
                  marginBottom: 10,
                }}
              >
                <span
                  style={{
                    display: "inline-block",
                    width: 18,
                    height: 18,
                    border: "2.5px solid rgba(255,255,255,0.3)",
                    borderTopColor: "#fff",
                    borderRadius: "50%",
                    animation: "spin 0.8s linear infinite",
                  }}
                />
                <strong style={{ color: "#fff", fontSize: "1rem" }}>Royal AI is extracting…</strong>
              </div>
              <p style={{ margin: 0, color: "rgba(255,255,255,0.5)", fontSize: "0.84rem" }}>
                Reading your invoice and extracting item codes, batches, and quantities
              </p>
            </div>
          </div>
        </div>
      )}

      {/* Royal AI Extraction Preview Modal */}
      {showExtractionPreview && extracted && (
        <div
          style={{
            position: "fixed",
            inset: 0,
            zIndex: 1100,
            background: "rgba(0,0,0,0.75)",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            padding: "20px",
          }}
          onClick={() => setShowExtractionPreview(false)}
        >
          <div
            style={{
              background: "#fff",
              borderRadius: 12,
              maxWidth: 640,
              width: "100%",
              maxHeight: "85vh",
              overflow: "auto",
            }}
            onClick={(e) => e.stopPropagation()}
          >
            {/* Header */}
            <div
              style={{
                background: "#0a0e1a",
                padding: "18px 22px",
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
              }}
            >
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <span style={{ fontSize: "1.2rem", color: "#fff" }}>✦</span>
                <div>
                  <strong style={{ color: "#fff", fontSize: "1rem", fontWeight: 800 }}>
                    Royal AI — Invoice Extracted
                  </strong>
                  <p style={{ margin: "2px 0 0", color: "rgba(255,255,255,0.6)", fontSize: "0.8rem" }}>
                    This invoice will be saved separately and linked to the sheet
                  </p>
                </div>
              </div>
              <button
                onClick={() => setShowExtractionPreview(false)}
                style={{
                  background: "rgba(255,255,255,0.15)",
                  border: "none",
                  color: "#fff",
                  borderRadius: 6,
                  padding: "6px 10px",
                  cursor: "pointer",
                  fontSize: "0.9rem",
                }}
              >
                ✕
              </button>
            </div>

            {/* Body */}
            <div style={{ padding: 22 }}>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 20 }}>
                {([
                  ["Document #", extracted.document_number],
                  ["Document Date", extracted.document_date],
                  ["Reference", extracted.reference_number],
                  ["Warehouse", extracted.warehouse_name],
                  ["Item Code", extracted.item_code],
                  ["Item Name", extracted.item_name],
                  ["Batch #", extracted.batch_number],
                  ["Supplier", extracted.supplier_name],
                ] as [string, string | null | undefined][])
                  .filter(([, v]) => v)
                  .map(([label, value]) => (
                    <div
                      key={label}
                      style={{
                        padding: "10px 12px",
                        background: "#f9fbff",
                        borderRadius: 8,
                        border: "1px solid var(--line)",
                      }}
                    >
                      <p
                        style={{
                          margin: 0,
                          color: "var(--muted)",
                          fontSize: "0.7rem",
                          textTransform: "uppercase",
                          letterSpacing: "0.06em",
                          fontWeight: 600,
                        }}
                      >
                        {label}
                      </p>
                      <p
                        style={{
                          margin: "3px 0 0",
                          fontWeight: 600,
                          color: "var(--ink)",
                          fontSize: "0.88rem",
                          wordBreak: "break-word",
                        }}
                      >
                        {value}
                      </p>
                    </div>
                  ))}
              </div>

              <div
                style={{
                  background: "#f0f4ff",
                  border: "1px solid rgba(59,91,219,0.2)",
                  borderRadius: 8,
                  padding: "12px 14px",
                  marginBottom: 18,
                  fontSize: "0.84rem",
                  color: "var(--brand)",
                }}
              >
                ✓ This invoice data will be saved to a separate collection and linked to the sheet.
              </div>

              <div style={{ display: "flex", gap: 10 }}>
                <button
                  type="button"
                  onClick={applyExtraction}
                  style={{
                    flex: 1,
                    padding: "10px 22px",
                    borderRadius: 8,
                    border: "none",
                    background: BRAND_GRADIENT,
                    color: "#fff",
                    fontSize: "0.88rem",
                    fontWeight: 600,
                    cursor: "pointer",
                    boxShadow: BRAND_SHADOW,
                  }}
                >
                  Confirm & Close
                </button>
                <button
                  type="button"
                  onClick={() => {
                    setExtracted(null);
                    setShowExtractionPreview(false);
                  }}
                  style={{
                    padding: "10px 22px",
                    borderRadius: 8,
                    border: "1.5px solid rgba(0,0,0,0.12)",
                    background: "#fff",
                    color: "#495057",
                    fontSize: "0.88rem",
                    fontWeight: 600,
                    cursor: "pointer",
                  }}
                >
                  Discard
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Confirmation Dialog */}
      {showConfirmDialog && (
        <div
          style={{
            position: "fixed",
            inset: 0,
            zIndex: 2000,
            background: "rgba(0,0,0,0.6)",
            backdropFilter: "blur(4px)",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            padding: "20px",
          }}
          onClick={() => setShowConfirmDialog(false)}
        >
          <div
            style={{
              background: "#fff",
              borderRadius: 12,
              maxWidth: "480px",
              width: "100%",
              boxShadow: "0 24px 64px rgba(15,22,48,0.22)",
            }}
            onClick={(e) => e.stopPropagation()}
          >
            <div
              style={{
                padding: "20px 24px",
                borderBottom: "1px solid rgba(0,0,0,0.07)",
              }}
            >
              <h3 style={{ margin: 0, fontSize: "1.1rem", fontWeight: 700, color: "var(--ink)" }}>
                Confirm Stock Movement Sheet
              </h3>
              <p style={{ margin: "6px 0 0", fontSize: "0.84rem", color: "var(--muted)" }}>
                Please confirm you want to submit this sheet for approval
              </p>
            </div>
            <div style={{ padding: "20px 24px" }}>
              <p style={{ margin: "0 0 20px", color: "var(--ink)", fontSize: "0.9rem" }}>
                Are you sure you want to submit this stock movement sheet for approval? This action will record the inbound inventory movement.
              </p>
              <div style={{ display: "flex", gap: 10, justifyContent: "flex-end" }}>
                <button
                  type="button"
                  onClick={() => setShowConfirmDialog(false)}
                  disabled={submitting}
                  style={{
                    padding: "10px 20px",
                    borderRadius: 8,
                    border: "1.5px solid rgba(0,0,0,0.12)",
                    background: "#fff",
                    color: "#495057",
                    fontSize: "0.88rem",
                    fontWeight: 600,
                    cursor: submitting ? "not-allowed" : "pointer",
                  }}
                >
                  Cancel
                </button>
                <button
                  type="button"
                  onClick={confirmSubmit}
                  disabled={submitting}
                  style={{
                    padding: "10px 20px",
                    borderRadius: 8,
                    border: "none",
                    background: submitting ? "#adb5bd" : BRAND_GRADIENT,
                    color: "#fff",
                    fontSize: "0.88rem",
                    fontWeight: 600,
                    cursor: submitting ? "not-allowed" : "pointer",
                    boxShadow: submitting ? "none" : BRAND_SHADOW,
                  }}
                >
                  {submitting ? "Submitting..." : "Yes, Submit for Approval"}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* CSS for spinner animation */}
      <style jsx>{`
        @keyframes spin {
          to {
            transform: rotate(360deg);
          }
        }
      `}</style>
    </>
  );
}

// Helper function to format numbers
function formatNumber(value: number): string {
  return value.toLocaleString('en-US', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
}

// Smaller summary card component
function SummaryCardSmall({
  label,
  value,
  unit,
  subUnit,
  highlight,
  danger,
}: {
  label: string;
  value: string;
  unit: string;
  subUnit?: string;
  highlight?: boolean;
  danger?: boolean;
}) {
  return (
    <div
      style={{
        background: danger ? "#fff5f5" : "#fff",
        borderRadius: 6,
        padding: "8px 10px",
        border: `1px solid ${danger ? "rgba(214,69,69,0.2)" : "rgba(59,91,219,0.12)"}`,
      }}
    >
      <p style={{ margin: 0, fontSize: "0.65rem", color: danger ? "var(--danger)" : "var(--muted)", textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 600 }}>
        {label}
      </p>
      <p style={{ margin: "3px 0 0", fontSize: "1.1rem", fontWeight: 800, color: danger ? "var(--danger)" : highlight ? "var(--brand)" : "var(--ink)", lineHeight: 1 }}>
        {value}
      </p>
      <p style={{ margin: "2px 0 0", fontSize: "0.68rem", color: "var(--muted)" }}>{unit}</p>
      {subUnit && (
        <p style={{ margin: "2px 0 0", fontSize: "0.62rem", color: "var(--muted)", fontStyle: "italic" }}>({subUnit})</p>
      )}
    </div>
  );
}
