"use client";

import React, { useState } from "react";
import type { WarehouseRecord, ItemRecord } from "@/lib/api";
import { generateUUID } from "@/lib/uuid";
import ItemAutocomplete from "@/app/components/ItemAutocomplete";

/**
 * ItemsTable Component (Redesigned)
 *
 * Dynamic row-based table where users add items on-demand.
 * Features:
 * - Autocomplete item code input
 * - API lookup with debounce (350ms) or Enter key
 * - Single quantity input (applies to all selected warehouses)
 * - Expandable rows for detailed item information
 * - Add/remove row functionality
 * - No "Enter Warehouses" button needed
 */

// Brand colors
const BRAND = "#4c6fff";

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

export interface SheetRow {
  id: string; // Unique row ID
  itemId: string; // Empty until item selected
  itemCode: string;
  itemName: string;
  barcode: string;
  blend: string;
  grainType: string;
  varietyType: string;
  processType: string;
  coo: string;
  unit: string;
  bagWeightKg: number | null;
  batchNumber: string;
  expiryDate: string;
  quantity: string; // Single quantity input
  warehouseBags: Record<string, string>; // Auto-populated from quantity
  totalMtOverride: string;
}

interface ItemsTableProps {
  rows: SheetRow[];
  selectedWarehouses: string[];
  warehouses: WarehouseRecord[];
  items: ItemRecord[]; // For autocomplete
  onRowUpdate: (rowId: string, updates: Partial<SheetRow>) => void;
  onAddRow: () => void;
  onRemoveRow: (rowId: string) => void;
  currentTotalMt: number;
  threshold: number;
  onError?: (message: string) => void; // For showing snackbar errors
}

export default function ItemsTable({
  rows,
  selectedWarehouses,
  warehouses,
  items,
  onRowUpdate,
  onAddRow,
  onRemoveRow,
  currentTotalMt,
  threshold,
  onError,
}: ItemsTableProps) {
  const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set());

  // Toggle row expansion
  function toggleRowExpansion(rowId: string) {
    setExpandedRows(prev => {
      const next = new Set(prev);
      if (next.has(rowId)) {
        next.delete(rowId);
      } else {
        next.add(rowId);
      }
      return next;
    });
  }

  // Calculate row totals
  function rowTotalBags(row: SheetRow): number {
    return Number(row.quantity) || 0;
  }

  function rowTotalMt(row: SheetRow): number {
    if (row.totalMtOverride !== "") {
      const v = Number(row.totalMtOverride);
      return isNaN(v) ? 0 : v;
    }
    if (row.bagWeightKg == null || row.bagWeightKg <= 0) return 0;
    return Number(((rowTotalBags(row) * row.bagWeightKg) / 1000).toFixed(4));
  }

  // Calculate grand totals
  const grandTotalBags = rows.reduce((s, r) => s + rowTotalBags(r), 0);
  const grandTotalMt = rows.reduce((s, r) => s + rowTotalMt(r), 0);
  const totalEmpty = Math.max(0, threshold - currentTotalMt - grandTotalMt);

  // Styles
  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",
  };

  const numCell: React.CSSProperties = {
    ...inCell,
    minWidth: 90,
    textAlign: "right",
  };

  const calcCell: React.CSSProperties = {
    background: "#f0f4ff",
    color: "var(--brand)",
    fontWeight: 700,
    fontSize: "0.88rem",
    padding: "9px 10px",
    borderRadius: 6,
    border: "1px solid rgba(59,91,219,0.15)",
    whiteSpace: "nowrap",
    display: "block",
    textAlign: "right",
    minWidth: 80,
  };

  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: "1200px" }}>
            <thead>
              <tr>
                <th style={{ ...thStyle, minWidth: 40 }}></th>
                <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: 130 }}>Batch #</th>
                <th style={{ ...thStyle, minWidth: 140 }}>Expiry Date</th>
                <th style={{ ...thStyle, minWidth: 120, textAlign: "right" }}>Quantity (Bags)</th>
                <th style={{ ...thStyle, minWidth: 100, textAlign: "right" }}>Total MT</th>
                <th style={{ ...thStyle, minWidth: 60 }}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {rows.length === 0 ? (
                <tr>
                  <td colSpan={9} 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) => {
                  const tb = rowTotalBags(row);
                  const tm = rowTotalMt(row);
                  const hasData = tb > 0;
                  const isExpanded = expandedRows.has(row.id);

                  return (
                    <React.Fragment key={row.id}>
                      {/* Main Row */}
                      <tr
                        style={{
                          borderBottom: isExpanded ? "none" : "1px solid var(--line)",
                          background: hasData ? "rgba(59,91,219,0.03)" : undefined,
                        }}
                      >
                        {/* Expand/Collapse Button */}
                        <td style={{ padding: "8px 6px", textAlign: "center" }}>
                          {row.itemId && (
                            <button
                              type="button"
                              onClick={() => toggleRowExpansion(row.id)}
                              style={{
                                background: "none",
                                border: "none",
                                cursor: "pointer",
                                color: "var(--muted)",
                                fontSize: "0.9rem",
                                padding: "4px",
                                display: "flex",
                                alignItems: "center",
                                justifyContent: "center",
                              }}
                              title={isExpanded ? "Hide details" : "Show details"}
                            >
                              {isExpanded ? "▼" : "▶"}
                            </button>
                          )}
                        </td>

                        {/* Row Number */}
                        <td style={{ padding: "10px", color: "var(--muted)", fontSize: "0.8rem", fontWeight: 600 }}>
                          {idx + 1}
                        </td>

                        {/* Item Code (Autocomplete) */}
                        <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 ?? "",
                                barcode: item.barcode ?? "",
                                blend: item.blend ?? "",
                                grainType: item.grainType ?? "",
                                varietyType: item.varietyType ?? "",
                                processType: item.processType ?? "",
                                coo: item.countryOfOrigin ?? "",
                                unit: item.unit ?? "",
                                bagWeightKg: item.bagWeightKg,
                              });
                            }}
                            onChange={(value) =>
                              onRowUpdate(row.id, {
                                itemId: "",
                                itemCode: value,
                                itemName: "",
                                barcode: "",
                                blend: "",
                                grainType: "",
                                varietyType: "",
                                processType: "",
                                coo: "",
                                unit: "",
                                bagWeightKg: null,
                              })
                            }
                            placeholder="Search item code or name..."
                            searchOnValueChange={false}
                          />
                        </td>

                        {/* Item Name (Autocomplete) */}
                        <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 ?? "",
                                barcode: item.barcode ?? "",
                                blend: item.blend ?? "",
                                grainType: item.grainType ?? "",
                                varietyType: item.varietyType ?? "",
                                processType: item.processType ?? "",
                                coo: item.countryOfOrigin ?? "",
                                unit: item.unit ?? "",
                                bagWeightKg: item.bagWeightKg,
                              });
                            }}
                            onChange={(value) =>
                              onRowUpdate(row.id, {
                                itemId: "",
                                itemCode: "",
                                itemName: value,
                                barcode: "",
                                blend: "",
                                grainType: "",
                                varietyType: "",
                                processType: "",
                                coo: "",
                                unit: "",
                                bagWeightKg: null,
                              })
                            }
                            placeholder="Search item name or code..."
                            searchOnValueChange={false}
                          />
                        </td>

                        {/* Batch Number */}
                        <td style={{ padding: "8px 10px" }}>
                          <input
                            style={inCell}
                            type="text"
                            value={row.batchNumber}
                            onChange={(e) => onRowUpdate(row.id, { batchNumber: e.target.value })}
                            placeholder="e.g. BATCH-001"
                            disabled={!row.itemId}
                          />
                        </td>

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

                        {/* Quantity (Single Input) */}
                        <td style={{ padding: "8px 10px" }}>
                          <input
                            style={numCell}
                            type="number"
                            min="0"
                            step="1"
                            value={row.quantity}
                            onChange={(e) => {
                              const quantity = e.target.value;
                              // Update warehouseBags for all selected warehouses
                              const warehouseBags: Record<string, string> = {};
                              selectedWarehouses.forEach(wId => {
                                warehouseBags[wId] = quantity;
                              });
                              onRowUpdate(row.id, { quantity, warehouseBags });
                            }}
                            placeholder="0"
                            disabled={!row.itemId || selectedWarehouses.length === 0}
                            title={
                              !row.itemId
                                ? "Select an item first"
                                : selectedWarehouses.length === 0
                                ? "Select warehouses from header first"
                                : `Quantity will be applied to ${selectedWarehouses.length} warehouse(s)`
                            }
                          />
                        </td>

                        {/* Total MT */}
                        <td style={{ padding: "8px 10px" }}>
                          {row.bagWeightKg != null && row.bagWeightKg > 0 ? (
                            <span
                              style={{
                                ...calcCell,
                                color: hasData ? "var(--brand)" : "var(--muted)",
                                background: hasData ? "#f0f4ff" : "#f4f7fd",
                                border: hasData ? "1px solid rgba(59,91,219,0.15)" : "1px solid var(--line)",
                              }}
                            >
                              {tm > 0 ? formatNumber(tm) : "—"}
                            </span>
                          ) : (
                            <input
                              style={{
                                ...numCell,
                                background: row.totalMtOverride !== "" ? "#f0f4ff" : "#fffbf0",
                                border: row.totalMtOverride !== "" ? "1.5px solid rgba(59,91,219,0.3)" : "1.5px solid #f0a500",
                                color: row.totalMtOverride !== "" ? "var(--brand)" : "#b07800",
                                fontWeight: 700,
                              }}
                              type="number"
                              min="0"
                              step="0.0001"
                              value={row.totalMtOverride}
                              placeholder="Enter MT"
                              onChange={(e) => onRowUpdate(row.id, { totalMtOverride: e.target.value })}
                              disabled={!row.itemId}
                              title="Bag weight not set for this item. Enter Total MT manually."
                            />
                          )}
                        </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>

                      {/* Expanded Details Row */}
                      {isExpanded && row.itemId && (
                        <tr style={{ borderBottom: "1px solid var(--line)", background: "#f9fbff" }}>
                          <td colSpan={9} style={{ padding: "16px 20px" }}>
                            <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: "12px" }}>
                              <DetailField label="Barcode" value={row.barcode} />
                              <DetailField label="Blend" value={row.blend} />
                              <DetailField label="Grain Type" value={row.grainType} />
                              <DetailField label="Variety/Type" value={row.varietyType} />
                              <DetailField label="Process Type" value={row.processType} />
                              <DetailField label="Country of Origin" value={row.coo} />
                              <DetailField label="Unit" value={row.unit} />
                              <DetailField
                                label="Bag Weight"
                                value={row.bagWeightKg ? `${row.bagWeightKg} kg` : "—"}
                              />
                            </div>
                          </td>
                        </tr>
                      )}
                    </React.Fragment>
                  );
                })
              )}

              {/* Grand Total Row */}
              {rows.length > 0 && (
                <tr style={{ background: "#f4f7fd", borderTop: "2px solid var(--line)" }}>
                  <td colSpan={6} style={{ padding: "12px 10px", fontWeight: 700, fontSize: "0.88rem", color: "var(--ink)" }}>
                    GRAND TOTAL
                  </td>
                  <td style={{ padding: "12px 10px", textAlign: "right", fontWeight: 800, fontSize: "0.96rem", color: "var(--ink)" }}>
                    {formatNumber(grandTotalBags)}
                  </td>
                  <td style={{ padding: "12px 10px", textAlign: "right", fontWeight: 800, fontSize: "0.96rem", color: "var(--brand)" }}>
                    {formatNumber(grandTotalMt)}
                  </td>
                  <td></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>
  );
}

// Helper Components

function DetailField({ label, value }: { label: string; value: string }) {
  return (
    <div>
      <p style={{ margin: 0, fontSize: "0.7rem", color: "var(--muted)", textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 600 }}>
        {label}
      </p>
      <p style={{ margin: "3px 0 0", fontWeight: 600, color: "var(--ink)", fontSize: "0.88rem" }}>
        {value || "—"}
      </p>
    </div>
  );
}

function SummaryCard({
  label,
  value,
  unit,
  highlight,
  danger,
}: {
  label: string;
  value: string;
  unit: string;
  highlight?: boolean;
  danger?: boolean;
}) {
  return (
    <div
      style={{
        background: danger ? "#fff5f5" : "#fff",
        borderRadius: 8,
        padding: "12px 14px",
        border: `1px solid ${danger ? "rgba(214,69,69,0.2)" : "rgba(59,91,219,0.12)"}`,
      }}
    >
      <p style={{ margin: 0, fontSize: "0.7rem", color: danger ? "var(--danger)" : "var(--muted)", textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 600 }}>
        {label}
      </p>
      <p style={{ margin: "4px 0 0", fontSize: "1.3rem", fontWeight: 800, color: danger ? "var(--danger)" : highlight ? "var(--brand)" : "var(--ink)", lineHeight: 1 }}>
        {value}
      </p>
      <p style={{ margin: "2px 0 0", fontSize: "0.72rem", color: "var(--muted)" }}>{unit}</p>
    </div>
  );
}

// Smaller summary card for top placement
function SummaryCardSmall({
  label,
  value,
  unit,
  highlight,
  danger,
}: {
  label: string;
  value: string;
  unit: 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>
    </div>
  );
}

// Helper function to create an empty row
export function createEmptyRow(): SheetRow {
  return {
    id: generateUUID(),
    itemId: "",
    itemCode: "",
    itemName: "",
    barcode: "",
    blend: "",
    grainType: "",
    varietyType: "",
    processType: "",
    coo: "",
    unit: "",
    bagWeightKg: null,
    batchNumber: "",
    expiryDate: "",
    quantity: "",
    warehouseBags: {},
    totalMtOverride: "",
  };
}
