"use client";

import React, { useState, useEffect, useRef } from "react";
import type { WarehouseRecord, ItemRecord } from "@/lib/api";
import { createStockOut, getStockMovementSheets, getBatches } from "@/lib/api";
import { generateNextSerialNumber } from "../stock-in/serialNumberUtils";
import WarehouseMultiSelect from "../stock-in/WarehouseMultiSelect";
import ExpiryReferenceModal from "./ExpiryReferenceModal";
import { generateUUID } from "@/lib/uuid";
import ItemAutocomplete from "@/app/components/ItemAutocomplete";

/**
 * StockOutModal Component
 *
 * Modal for creating stock-out sheets (matching stock-in structure).
 * Features:
 * - Serial number (SMS-OUT-XXXXX format)
 * - Date selection
 * - Multi-warehouse selection
 * - Items table with add/remove rows
 * - Item code input with debounced API lookup
 * - Form validation and submission
 */

// Brand colors
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 StockOutRow {
  id: string;
  itemId: string;
  itemCode: string;
  itemName: string;
  batchNumber: string; // Batch number - REQUIRED
  batchId: string; // Batch ID for backend
  expiryDate: string;
  availableBags: number | null; // Available bags from DB (for validation)
  availableMt: number | null; // Available MT from DB (for reference)
  totalBags: number | null; // User input - bags to stock out
  totalMt: number | null; // Calculated from totalBags
  bagWeightKg: number | null; // Bag weight for calculations
}

interface BatchSelection {
  batchNumber: string;
  batchId: string;
  expiryDate: string;
  totalBags: number;
  totalMt: number;
}

function createEmptyStockOutRow(): StockOutRow {
  return {
    id: generateUUID(),
    itemId: "",
    itemCode: "",
    itemName: "",
    batchNumber: "",
    batchId: "",
    expiryDate: "",
    availableBags: null,
    availableMt: null,
    totalBags: null,
    totalMt: null,
    bagWeightKg: null,
  };
}

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

export default function StockOutModal({
  isOpen,
  onClose,
  onSuccess,
  warehouses,
}: StockOutModalProps) {
  // Serial number and date
  const [serialNumber, setSerialNumber] = useState<string>("SMS-OUT-00001");
  const [entryDate, setEntryDate] = useState<string>("");

  // Warehouse selection
  const [selectedWarehouses, setSelectedWarehouses] = useState<string[]>([]);

  // Row data
  const [rows, setRows] = useState<StockOutRow[]>([]);

  // Submission state
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [toast, setToast] = useState<string | null>(null);
  const [showConfirmDialog, setShowConfirmDialog] = useState(false);
  const [showExpiryReference, setShowExpiryReference] = useState(false);

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

  async function initializeModal() {
    // Generate serial number for stock-out
    try {
      const sheets = await getStockMovementSheets();
      const outSheets = sheets.filter(s => s.documentNumber?.startsWith("SMS-OUT-"));
      const nextNum = outSheets.length + 1;
      setSerialNumber(`SMS-OUT-${String(nextNum).padStart(5, "0")}`);
    } catch (error) {
      console.error("Error generating serial number:", error);
      setSerialNumber("SMS-OUT-00001");
    }

    // Set current date
    const today = new Date().toISOString().split("T")[0];
    setEntryDate(today);

    // Initialize with empty rows
    setRows([]);

    // Reset state
    setSelectedWarehouses([]);
    setError(null);
    setSuccess(null);
    setToast(null);
    setShowConfirmDialog(false);
  }

  // Handle warehouse selection change
  function handleWarehouseChange(newWarehouses: string[]) {
    setSelectedWarehouses(newWarehouses);
  }

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

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

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

  function handleBatchSelection(rowId: string, selections: BatchSelection[]) {
    if (selections.length === 0) return;

    setRows((prev) => {
      const rowIndex = prev.findIndex((r) => r.id === rowId);
      if (rowIndex === -1) return prev;

      const sourceRow = prev[rowIndex];
      const existingKeys = new Set(
        prev
          .filter((row) => row.id !== rowId)
          .map((row) => `${row.itemId}|${row.batchNumber}|${row.expiryDate}`),
      );
      const nextRows = [...prev];

      selections.forEach((selection, index) => {
        const updates: Partial<StockOutRow> = {
          batchNumber: selection.batchNumber,
          batchId: selection.batchId,
          expiryDate: selection.expiryDate,
          availableBags: selection.totalBags,
          availableMt: selection.totalMt,
          totalBags: null,
          totalMt: null,
        };

        if (index === 0) {
          nextRows[rowIndex] = { ...sourceRow, ...updates };
          return;
        }

        const key = `${sourceRow.itemId}|${selection.batchNumber}|${selection.expiryDate}`;
        if (existingKeys.has(key)) return;
        existingKeys.add(key);
        nextRows.splice(rowIndex + index, 0, {
          ...sourceRow,
          id: generateUUID(),
          ...updates,
        });
      });

      return nextRows;
    });
  }

  // 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
    if (selectedWarehouses.length === 0) {
      setError("Please select at least one warehouse.");
      return;
    }

    // Filter rows that have an item selected
    const activeRows = rows.filter((r) => r.itemId);

    if (activeRows.length === 0) {
      setError("Add at least one item before submitting.");
      return;
    }

    // Validate that all rows have loaded stock data
    const rowsWithMissingData = activeRows.filter(
      (r) => r.totalMt === null || r.totalMt === undefined
    );

    if (rowsWithMissingData.length > 0) {
      const itemCodes = rowsWithMissingData.map((r) => r.itemCode).join(", ");
      setError(
        `Cannot submit: Stock data is not loaded for items: ${itemCodes}. ` +
        `Please wait a moment for the data to load, or re-enter the item codes.`
      );
      return;
    }

    // Validate that all rows have batch number selected
    const rowsWithoutBatch = activeRows.filter((r) => !r.batchNumber || !r.batchId);

    if (rowsWithoutBatch.length > 0) {
      const itemCodes = rowsWithoutBatch.map((r) => r.itemCode).join(", ");
      setError(
        `Cannot submit: Batch number is required for items: ${itemCodes}. ` +
        `Please select a batch number for each item.`
      );
      return;
    }

    // Validate that user has entered bags quantity
    const rowsWithoutBags = activeRows.filter((r) => r.totalBags === null || r.totalBags <= 0);

    if (rowsWithoutBags.length > 0) {
      const itemCodes = rowsWithoutBags.map((r) => r.itemCode).join(", ");
      setError(
        `Cannot submit: Please enter the number of bags to stock out for items: ${itemCodes}.`
      );
      return;
    }

    // Validate that bags don't exceed available quantity
    const rowsExceedingLimit = activeRows.filter(
      (r) => r.availableBags !== null && r.totalBags !== null && r.totalBags > r.availableBags
    );

    if (rowsExceedingLimit.length > 0) {
      const details = rowsExceedingLimit.map(
        (r) => `${r.itemCode}: Entered ${r.totalBags} bags, but only ${r.availableBags} available`
      ).join("\n");
      setError(
        `Cannot submit: Quantity exceeds available stock:\n\n${details}`
      );
      return;
    }

    setSubmitting(true);
    setError(null);

    try {
      // Submit stock-out for each warehouse + item combination
      const promises: Promise<any>[] = [];

      console.log("🚀 Starting stock-out submission...");
      console.log("Active rows:", activeRows);
      console.log("Selected warehouses:", selectedWarehouses);

      activeRows.forEach((row) => {
        // Use the total MT available as the quantity to stock out
        // Validation above ensures totalMt is a number
        const quantity = row.totalMt ?? 0;
        console.log(`Row ${row.itemCode}:`, {
          totalMt: row.totalMt,
          quantity,
        });
        
        // Create stock-out for each warehouse with the total MT available
        selectedWarehouses.forEach((warehouseId) => {
          console.log(`Creating stock-out: warehouse=${warehouseId}, item=${row.itemId}, batch=${row.batchId}, qty=${quantity} MT`);
          promises.push(
            createStockOut({
              warehouseId,
              itemId: row.itemId,
                batchId: row.batchId,
                expiryDate: row.expiryDate || undefined,
                quantityMt: quantity,
            })
          );
        });
      });

      console.log(`Total API calls to make: ${promises.length}`);

      console.log("Executing API calls...");
      const results = await Promise.all(promises);
      console.log("✅ API calls successful:", results);

      setSuccess(
        `Stock-out transaction${promises.length > 1 ? "s" : ""} created successfully.`
      );

      // Close modal after 1.5 seconds
      setTimeout(() => {
        handleClose();
        onSuccess();
      }, 1500);
    } catch (err) {
      console.error("❌ Stock-out submission error:", 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) {
        handleClose();
      }
    }

    document.addEventListener("keydown", handleEscape);
    return () => document.removeEventListener("keydown", handleEscape);
  }, [isOpen]); // 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;

  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-Out Process
              </h2>
              <p
                style={{
                  margin: "4px 0 0",
                  fontSize: "0.84rem",
                  color: "rgba(255,255,255,0.82)",
                }}
              >
                Select warehouses and add items to stock out
              </p>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <button
                type="button"
                onClick={() => setShowExpiryReference(true)}
                style={{
                  background: "rgba(255,255,255,0.15)",
                  border: "1px solid rgba(255,255,255,0.3)",
                  color: "#fff",
                  borderRadius: 8,
                  padding: "8px 14px",
                  cursor: "pointer",
                  fontSize: "0.84rem",
                  fontWeight: 600,
                  display: "flex",
                  alignItems: "center",
                  gap: 6,
                }}
                title="View expiry dates across inventory"
              >
                📅 Expiry Reference
              </button>
              <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>
          </div>

          {/* Modal Body */}
          <div style={{ flex: 1, overflowY: "auto", padding: "24px 26px" }}>
            <form onSubmit={handleSubmit} id="stock-out-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>
              )}

              {/* Success Message */}
              {success && (
                <div
                  style={{
                    marginBottom: 18,
                    padding: "12px 16px",
                    borderRadius: 8,
                    background: "var(--brand-soft)",
                    border: "1px solid rgba(59,91,219,0.3)",
                    color: "var(--brand)",
                    fontSize: "0.88rem",
                    display: "flex",
                    alignItems: "center",
                    gap: 10,
                  }}
                >
                  <span style={{ fontSize: "1.2rem" }}>✓</span>
                  <span style={{ flex: 1 }}>{success}</span>
                </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>
              )}

              {/* Sheet Header */}
              <div className="card" style={{ marginBottom: 20, padding: "18px 20px" }}>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr 1fr", gap: 16 }}>
                  {/* Serial Number */}
                  <div>
                    <label
                      style={{
                        display: "block",
                        marginBottom: 6,
                        fontSize: "0.78rem",
                        fontWeight: 600,
                        color: "var(--muted)",
                        textTransform: "uppercase",
                        letterSpacing: "0.06em",
                      }}
                    >
                      Document Number
                    </label>
                    <div
                      style={{
                        padding: "10px 12px",
                        borderRadius: 8,
                        background: "#f4f7fd",
                        border: "1.5px solid var(--line)",
                        fontSize: "0.88rem",
                        fontWeight: 700,
                        color: "var(--brand)",
                        fontFamily: "monospace",
                      }}
                    >
                      {serialNumber}
                    </div>
                  </div>

                  {/* Date */}
                  <div>
                    <label
                      style={{
                        display: "block",
                        marginBottom: 6,
                        fontSize: "0.78rem",
                        fontWeight: 600,
                        color: "var(--muted)",
                        textTransform: "uppercase",
                        letterSpacing: "0.06em",
                      }}
                    >
                      Date
                    </label>
                    <input
                      type="date"
                      value={entryDate}
                      onChange={(e) => setEntryDate(e.target.value)}
                      style={{
                        width: "100%",
                        padding: "10px 12px",
                        borderRadius: 8,
                        border: "1.5px solid var(--line)",
                        fontSize: "0.88rem",
                        fontFamily: "inherit",
                        color: "var(--ink)",
                        outline: "none",
                        boxSizing: "border-box",
                      }}
                    />
                  </div>

                  {/* Warehouse Selection */}
                  <div>
                    <label
                      style={{
                        display: "block",
                        marginBottom: 6,
                        fontSize: "0.78rem",
                        fontWeight: 600,
                        color: "var(--muted)",
                        textTransform: "uppercase",
                        letterSpacing: "0.06em",
                      }}
                    >
                      Warehouses <span style={{ color: "var(--danger)" }}>*</span>
                    </label>
                    <WarehouseMultiSelect
                      warehouses={warehouses}
                      selected={selectedWarehouses}
                      onChange={handleWarehouseChange}
                    />
                  </div>
                </div>
              </div>

              {/* Items Table */}
                <StockOutItemsTable
                  rows={rows}
                  selectedWarehouses={selectedWarehouses}
                  onRowUpdate={handleRowUpdate}
                  onBatchSelection={handleBatchSelection}
                  onAddRow={handleAddRow}
                  onRemoveRow={handleRemoveRow}
                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}
              disabled={submitting}
              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: submitting ? "not-allowed" : "pointer",
                opacity: submitting ? 0.5 : 1,
              }}
            >
              Cancel
            </button>
            <button
              type="submit"
              form="stock-out-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"
                  >
                    <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" />
                    <polyline points="22 4 12 14.01 9 11.01" />
                  </svg>
                  Create Stock-Out
                </>
              )}
            </button>
          </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-Out Creation
              </h3>
              <p style={{ margin: "6px 0 0", fontSize: "0.84rem", color: "var(--muted)" }}>
                Please confirm you want to create this stock-out transaction
              </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 create this stock-out sheet? This action will record the outbound 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 ? "Creating..." : "Yes, Create Stock-Out"}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Expiry Reference Modal */}
      <ExpiryReferenceModal
        isOpen={showExpiryReference}
        onClose={() => setShowExpiryReference(false)}
      />

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

// Stock-Out Items Table Component
interface StockOutItemsTableProps {
  rows: StockOutRow[];
  selectedWarehouses: string[];
  onRowUpdate: (rowId: string, updates: Partial<StockOutRow>) => void;
  onBatchSelection: (rowId: string, selections: BatchSelection[]) => void;
  onAddRow: () => void;
  onRemoveRow: (rowId: string) => void;
  onError?: (message: string) => void;
}

function StockOutItemsTable({
  rows,
  selectedWarehouses,
  onRowUpdate,
  onBatchSelection,
  onAddRow,
  onRemoveRow,
  onError,
}: StockOutItemsTableProps) {
  const thStyle: React.CSSProperties = {
    padding: "12px 10px",
    textAlign: "left",
    color: "var(--muted)",
    fontSize: "0.75rem",
    textTransform: "uppercase",
    letterSpacing: "0.06em",
    whiteSpace: "nowrap",
    borderBottom: "2px solid var(--line)",
    background: "#f4f7fd",
    position: "sticky",
    top: 0,
    zIndex: 1,
  };

  const inCell: React.CSSProperties = {
    padding: "9px 10px",
    borderRadius: 6,
    border: "1.5px solid var(--line)",
    background: "#fff",
    fontSize: "0.88rem",
    fontFamily: "inherit",
    color: "var(--ink)",
    outline: "none",
    width: "100%",
    minWidth: 110,
    boxSizing: "border-box",
  };

  return (
    <div style={{ marginBottom: 18 }}>
      <div className="card" style={{ padding: 0, overflow: "visible" }}>
        <div style={{ overflowX: "auto", overflowY: "visible" }}>
          <table style={{ borderCollapse: "collapse", width: "100%", minWidth: "1000px" }}>
            <thead>
              <tr>
                <th style={{ ...thStyle, minWidth: 40 }}>#</th>
                <th style={{ ...thStyle, minWidth: 150 }}>Item Code</th>
                <th style={{ ...thStyle, minWidth: 200 }}>Item Name</th>
                <th style={{ ...thStyle, minWidth: 140 }}>Batch Number <span style={{ color: "#d64545" }}>*</span></th>
                <th style={{ ...thStyle, minWidth: 110, textAlign: "right" }}>Total Bags</th>
                <th style={{ ...thStyle, minWidth: 110, textAlign: "right" }}>Total MT</th>
                <th style={{ ...thStyle, minWidth: 140 }}>Expiry Date</th>
                <th style={{ ...thStyle, minWidth: 60 }}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {rows.length === 0 ? (
                <tr>
                  <td colSpan={8} style={{ padding: "40px", textAlign: "center", color: "var(--muted)" }}>
                    <p style={{ margin: "0 0 12px", fontSize: "0.9rem" }}>No items added yet</p>
                    <button
                      type="button"
                      onClick={onAddRow}
                      style={{
                        padding: "8px 18px",
                        borderRadius: 6,
                        border: `1.5px solid ${BRAND}`,
                        background: "#fff",
                        color: BRAND,
                        fontSize: "0.85rem",
                        fontWeight: 600,
                        cursor: "pointer",
                      }}
                    >
                      + Add First Item
                    </button>
                  </td>
                </tr>
              ) : (
                rows.map((row, idx) => (
                  <tr
                    key={row.id}
                    style={{
                      borderBottom: "1px solid var(--line)",
                      background: row.itemId ? "rgba(59,91,219,0.03)" : undefined,
                    }}
                  >
                    {/* Row Number */}
                    <td style={{ padding: "10px", color: "var(--muted)", fontSize: "0.8rem", fontWeight: 600 }}>
                      {idx + 1}
                    </td>

                    {/* Item Code */}
                    <td style={{ padding: "8px 10px", position: "relative", overflow: "visible" }}>
                      <ItemAutocomplete
                        value={row.itemCode}
                        onSelect={(item) => {
                          onRowUpdate(row.id, {
                            itemId: item._id,
                            itemCode: item.itemCode,
                            itemName: item.itemName ?? item.description ?? "",
                            bagWeightKg: item.bagWeightKg,
                            batchNumber: "",
                            batchId: "",
                            expiryDate: "",
                            availableBags: null,
                            availableMt: null,
                            totalBags: null,
                            totalMt: null,
                          });
                        }}
                        onChange={(value) =>
                          onRowUpdate(row.id, {
                            itemId: "",
                            itemCode: value,
                            itemName: "",
                            batchNumber: "",
                            batchId: "",
                            expiryDate: "",
                            availableBags: null,
                            availableMt: null,
                            totalBags: null,
                            totalMt: null,
                            bagWeightKg: null,
                          })
                        }
                        placeholder="Search item code or name..."
                        searchOnValueChange={false}
                      />
                    </td>

                    {/* Item Name */}
                    <td style={{ padding: "8px 10px", position: "relative", overflow: "visible" }}>
                      <ItemAutocomplete
                        value={row.itemName}
                        getInputValue={(item) => item.itemName ?? item.description ?? item.itemCode}
                        onSelect={(item) => {
                          onRowUpdate(row.id, {
                            itemId: item._id,
                            itemCode: item.itemCode,
                            itemName: item.itemName ?? item.description ?? "",
                            bagWeightKg: item.bagWeightKg,
                            batchNumber: "",
                            batchId: "",
                            expiryDate: "",
                            availableBags: null,
                            availableMt: null,
                            totalBags: null,
                            totalMt: null,
                          });
                        }}
                        onChange={(value) =>
                          onRowUpdate(row.id, {
                            itemId: "",
                            itemCode: "",
                            itemName: value,
                            batchNumber: "",
                            batchId: "",
                            expiryDate: "",
                            availableBags: null,
                            availableMt: null,
                            totalBags: null,
                            totalMt: null,
                            bagWeightKg: null,
                          })
                        }
                        placeholder="Search item name or code..."
                        searchOnValueChange={false}
                      />
                    </td>

                    {/* Batch Number (Required) */}
                    <td style={{ padding: "8px 10px", position: "relative", overflow: "visible" }}>
                      <BatchNumberInput
                        value={row.batchNumber}
                        itemId={row.itemId}
                        selectedWarehouses={selectedWarehouses}
                          onSelect={(selections) => onBatchSelection(row.id, selections)}
                        onChange={(value) => onRowUpdate(row.id, { batchNumber: value })}
                        disabled={!row.itemId}
                      />
                    </td>

                    {/* Total Bags (User Input with Validation) */}
                    <td style={{ padding: "8px 10px" }}>
                      <div style={{ position: "relative" }}>
                        <input
                          type="number"
                          min="0"
                          value={row.totalBags !== null ? row.totalBags : ""}
                          onChange={(e) => {
                            const value = e.target.value;
                            const bags = value === "" ? null : Number(value);
                            
                            // Calculate MT from bags
                            let mt = null;
                            if (bags !== null && row.bagWeightKg) {
                              mt = (bags * row.bagWeightKg) / 1000;
                            }
                            
                            onRowUpdate(row.id, { totalBags: bags, totalMt: mt });
                          }}
                          placeholder={row.availableBags !== null ? `Max: ${row.availableBags}` : "Enter bags"}
                          disabled={!row.batchId}
                          style={{
                            padding: "9px 10px",
                            borderRadius: 6,
                            border: `1.5px solid ${
                              row.totalBags !== null && row.availableBags !== null && row.totalBags > row.availableBags
                                ? "#d64545"
                                : row.totalBags !== null
                                ? "#4caf50"
                                : "var(--line)"
                            }`,
                            background: row.totalBags !== null ? "#f0fff4" : "#fff",
                            fontSize: "0.88rem",
                            fontFamily: "inherit",
                            color: "var(--ink)",
                            outline: "none",
                            width: "100%",
                            boxSizing: "border-box",
                            textAlign: "right",
                          }}
                        />
                        {row.availableBags !== null && (
                          <div
                            style={{
                              fontSize: "0.72rem",
                              color: "var(--muted)",
                              marginTop: 2,
                              textAlign: "right",
                            }}
                          >
                            Available: {row.availableBags.toLocaleString()} bags
                          </div>
                        )}
                        {row.totalBags !== null && row.availableBags !== null && row.totalBags > row.availableBags && (
                          <div
                            style={{
                              fontSize: "0.72rem",
                              color: "#d64545",
                              marginTop: 2,
                              textAlign: "right",
                            }}
                          >
                            ⚠ Exceeds available quantity
                          </div>
                        )}
                      </div>
                    </td>

                    {/* Total MT (Calculated from bags) */}
                    <td style={{ padding: "8px 10px" }}>
                      <div
                        style={{
                          padding: "9px 10px",
                          borderRadius: 6,
                          background: row.totalMt !== null ? "#f0fff4" : "#f4f7fd",
                          color: row.totalMt !== null ? "#2d7a3e" : "var(--muted)",
                          fontSize: "0.88rem",
                          fontWeight: row.totalMt !== null ? 700 : 400,
                          minHeight: "38px",
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "flex-end",
                          fontFamily: row.totalMt !== null ? "monospace" : "inherit",
                        }}
                        title={
                          row.totalMt !== null
                            ? `Calculated: ${row.totalBags} bags × ${row.bagWeightKg}kg ÷ 1000`
                            : "Enter bags to calculate MT"
                        }
                      >
                        {row.totalMt !== null ? row.totalMt.toFixed(2) : "—"}
                      </div>
                      {row.availableMt !== null && (
                        <div
                          style={{
                            fontSize: "0.72rem",
                            color: "var(--muted)",
                            marginTop: 2,
                            textAlign: "right",
                          }}
                        >
                          Available: {row.availableMt.toFixed(2)} MT
                        </div>
                      )}
                    </td>

                    {/* Expiry Date (Optional) */}
                    <td style={{ padding: "8px 10px" }}>
                      <input
                        style={inCell}
                        type="date"
                        value={row.expiryDate}
                        onChange={(e) => onRowUpdate(row.id, { expiryDate: e.target.value })}
                        placeholder="Optional"
                        disabled={!row.itemId}
                      />
                    </td>

                    {/* Actions (Delete) */}
                    <td style={{ padding: "8px 10px", textAlign: "center" }}>
                      <button
                        type="button"
                        onClick={() => onRemoveRow(row.id)}
                        style={{
                          background: "none",
                          border: "none",
                          cursor: "pointer",
                          color: "#d64545",
                          padding: "4px 8px",
                          display: "inline-flex",
                          alignItems: "center",
                          justifyContent: "center",
                        }}
                        title="Remove item"
                      >
                        <svg
                          width="18"
                          height="18"
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          strokeWidth="2"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                        >
                          <polyline points="3 6 5 6 21 6" />
                          <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
                          <line x1="10" y1="11" x2="10" y2="17" />
                          <line x1="14" y1="11" x2="14" y2="17" />
                        </svg>
                      </button>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Add Row Button */}
      {rows.length > 0 && (
        <div style={{ marginTop: 12, display: "flex", justifyContent: "flex-start" }}>
          <button
            type="button"
            onClick={onAddRow}
            style={{
              padding: "10px 20px",
              borderRadius: 8,
              border: `1.5px solid ${BRAND}`,
              background: "#fff",
              color: BRAND,
              fontSize: "0.88rem",
              fontWeight: 600,
              cursor: "pointer",
              display: "flex",
              alignItems: "center",
              gap: 8,
            }}
          >
            <span style={{ fontSize: "1.1rem" }}>+</span>
            Add Item
          </button>
        </div>
      )}
    </div>
  );
}

// Batch Number Input Component
interface BatchNumberInputProps {
  value: string;
  itemId: string;
  selectedWarehouses: string[];
  onSelect: (selections: BatchSelection[]) => void;
  onChange: (value: string) => void;
  disabled?: boolean;
}

function BatchNumberInput({ value, itemId, selectedWarehouses, onSelect, onChange, disabled }: BatchNumberInputProps) {
  const [isLoading, setIsLoading] = useState(false);
  const [availableBatches, setAvailableBatches] = useState<Array<{
    batchNumber: string;
    batchId: string;
    expiryDate: string;
    totalBags: number;
    totalMt: number;
  }>>([]);
  const [showDropdown, setShowDropdown] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  const [dropdownPosition, setDropdownPosition] = useState({ top: 0, left: 0, width: 0 });

  // Fetch available batches when item is selected
  useEffect(() => {
    if (itemId && selectedWarehouses.length > 0) {
      fetchAvailableBatches();
    } else {
      setAvailableBatches([]);
    }
  }, [itemId, selectedWarehouses]); // eslint-disable-line react-hooks/exhaustive-deps

  // Close dropdown when clicking outside
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setShowDropdown(false);
      }
    }

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  // Update dropdown position when it opens
  useEffect(() => {
    if (showDropdown && inputRef.current) {
      const rect = inputRef.current.getBoundingClientRect();
      setDropdownPosition({
        top: rect.bottom + window.scrollY + 4,
        left: rect.left + window.scrollX,
        width: rect.width,
      });
    }
  }, [showDropdown]);

  async function fetchAvailableBatches() {
    if (!itemId || selectedWarehouses.length === 0) return;

    setIsLoading(true);
    try {
      const batchMap = new Map<string, {
        batchNumber: string;
        batchId: string;
        expiryDate: string;
        totalBags: number;
        totalMt: number;
      }>();

      // Fetch batches for each selected warehouse
      for (const warehouseId of selectedWarehouses) {
        try {
          const batches = await getBatches(itemId, warehouseId);
          
          for (const batch of batches) {
            const key = `${batch.batchNumber}|${batch.expiryDate}`;
            const existing = batchMap.get(key);
            const totalBags = batch.availableBags ?? Math.round((batch.availableMt * 1000) / 25);
            
            if (existing) {
              // Aggregate across warehouses
              existing.totalMt += batch.availableMt;
              existing.totalBags += totalBags;
            } else {
              batchMap.set(key, {
                batchNumber: batch.batchNumber,
                batchId: batch.id,
                expiryDate: batch.expiryDate,
                totalMt: batch.availableMt,
                totalBags,
              });
            }
          }
        } catch (err) {
          console.error(`Error fetching batches for warehouse ${warehouseId}:`, err);
        }
      }

      // Convert map to array
      const batches = Array.from(batchMap.values()).sort(
        (a, b) => a.batchNumber.localeCompare(b.batchNumber) || a.expiryDate.localeCompare(b.expiryDate)
      );
      setAvailableBatches(batches);
    } catch (err) {
      console.error("Error fetching available batches:", err);
      setAvailableBatches([]);
    } finally {
      setIsLoading(false);
    }
  }

  function handleBatchSelect(batch: typeof availableBatches[0]) {
    onChange(batch.batchNumber);
    const sameBatchSelections = availableBatches
      .filter((candidate) => candidate.batchNumber === batch.batchNumber)
      .sort((a, b) => {
        if (a.expiryDate === batch.expiryDate) return -1;
        if (b.expiryDate === batch.expiryDate) return 1;
        return a.expiryDate.localeCompare(b.expiryDate);
      });
    onSelect(sameBatchSelections);
    setShowDropdown(false);
  }

  return (
    <>
      <div style={{ position: "relative" }}>
        <input
          ref={inputRef}
          type="text"
          value={value}
          onChange={(e) => onChange(e.target.value)}
          onFocus={() => setShowDropdown(true)}
          placeholder={disabled ? "Select item first" : "Select batch..."}
          disabled={disabled || isLoading}
          style={{
            padding: "9px 10px",
            borderRadius: 6,
            border: `1.5px solid ${value ? "#4caf50" : "var(--line)"}`,
            background: value ? "#f0fff4" : disabled ? "#f8f9fb" : "#fff",
            fontSize: "0.88rem",
            fontFamily: "inherit",
            color: disabled ? "var(--muted)" : "var(--ink)",
            outline: "none",
            width: "100%",
            boxSizing: "border-box",
            cursor: disabled ? "not-allowed" : "pointer",
          }}
          readOnly
        />
      </div>

      {/* Dropdown - Rendered with fixed positioning to escape overflow containers */}
      {showDropdown && !disabled && availableBatches.length > 0 && (
        <div
          ref={dropdownRef}
          style={{
            position: "fixed",
            top: dropdownPosition.top,
            left: dropdownPosition.left,
            width: dropdownPosition.width,
            background: "#fff",
            border: "1.5px solid var(--line)",
            borderRadius: 8,
            boxShadow: "0 4px 12px rgba(0,0,0,0.15)",
            maxHeight: 200,
            overflowY: "auto",
            zIndex: 9999,
          }}
        >
          {availableBatches.map((batch, idx) => (
            <div
              key={idx}
              onClick={() => handleBatchSelect(batch)}
              style={{
                padding: "10px 12px",
                cursor: "pointer",
                borderBottom: idx < availableBatches.length - 1 ? "1px solid var(--line)" : "none",
                background: value === batch.batchNumber ? "#f0f4ff" : "#fff",
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.background = "#f0f4ff";
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.background = value === batch.batchNumber ? "#f0f4ff" : "#fff";
              }}
            >
              <div style={{ fontSize: "0.88rem", fontWeight: 600, color: "var(--ink)", marginBottom: 4 }}>
                {batch.batchNumber}
              </div>
              <div style={{ fontSize: "0.78rem", color: "var(--muted)" }}>
                Expiry: {new Date(batch.expiryDate).toLocaleDateString("en-AE")} • {batch.totalBags.toLocaleString()} bags • {batch.totalMt.toFixed(2)} MT
              </div>
            </div>
          ))}
        </div>
      )}

      {/* No batches available */}
      {showDropdown && !disabled && !isLoading && availableBatches.length === 0 && (
        <div
          ref={dropdownRef}
          style={{
            position: "fixed",
            top: dropdownPosition.top,
            left: dropdownPosition.left,
            width: dropdownPosition.width,
            background: "#fff",
            border: "1.5px solid var(--line)",
            borderRadius: 8,
            boxShadow: "0 4px 12px rgba(0,0,0,0.15)",
            padding: "12px",
            zIndex: 9999,
            fontSize: "0.84rem",
            color: "var(--muted)",
            textAlign: "center",
          }}
        >
          No batches available for selected warehouses
        </div>
      )}
    </>
  );
}
