"use client";

import React from "react";
import type { WarehouseRecord, ItemRecord } from "@/lib/api";

/**
 * ItemsTable Component
 *
 * Displays items with static properties and dynamic warehouse columns.
 * Supports "Enter Warehouses" button for focused quantity entry via WarehouseEntryModal.
 *
 * Design matches the premium patterns from the existing Stock In page.
 */

// 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 {
  itemId: string;
  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;
  warehouseBags: Record<string, string>;
  totalMtOverride: string; // only used when bagWeightKg is unknown
}

interface ItemsTableProps {
  rows: SheetRow[];
  selectedWarehouses: string[];
  warehouses: WarehouseRecord[];
  onRowUpdate: (itemId: string, updates: Partial<SheetRow>) => void;
  onOpenWarehouseModal: (rowIndex: number) => void;
  currentTotalMt: number;
  threshold: number;
}

export default function ItemsTable({
  rows,
  selectedWarehouses,
  warehouses,
  onRowUpdate,
  onOpenWarehouseModal,
  currentTotalMt,
  threshold,
}: ItemsTableProps) {
  
  // Calculate row totals
  function rowTotalBags(row: SheetRow): number {
    return Object.values(row.warehouseBags).reduce((s, v) => s + (Number(v) || 0), 0);
  }

  function rowTotalMt(row: SheetRow): number {
    // If user provided a manual override (only when bagWeightKg is null), use it
    if (row.totalMtOverride !== "") {
      const v = Number(row.totalMtOverride);
      return isNaN(v) ? 0 : v;
    }
    // Auto-calculate: Total MT = Total Bags × bagWeightKg ÷ 1000
    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);

  // Get warehouse name by ID
  function getWarehouseName(warehouseId: string): string {
    const warehouse = warehouses.find(w => w._id === warehouseId);
    return warehouse?.name || warehouseId;
  }

  // Count warehouses with quantities for a row
  function countWarehousesWithQuantities(row: SheetRow): number {
    return Object.values(row.warehouseBags).filter(v => Number(v) > 0).length;
  }

  // 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 roCell: React.CSSProperties = {
    background: "#f4f7fd",
    color: "var(--ink)",
    fontSize: "0.85rem",
    padding: "9px 10px",
    borderRadius: 6,
    border: "1px solid var(--line)",
    whiteSpace: "nowrap",
    overflow: "hidden",
    textOverflow: "ellipsis",
    display: "block",
    maxWidth: 160,
  };

  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 className="card" style={{ marginBottom: 18, padding: 0, overflow: "hidden" }}>
      <div style={{ overflowX: "auto" }}>
        <table style={{ borderCollapse: "collapse", width: "100%", minWidth: "1600px" }}>
          <thead>
            <tr>
              <th style={{ ...thStyle, minWidth: 40 }}>#</th>
              <th style={{ ...thStyle, minWidth: 80 }}>Code</th>
              <th style={{ ...thStyle, minWidth: 200 }}>Item Name</th>
              <th style={{ ...thStyle, minWidth: 120 }}>Barcode</th>
              <th style={{ ...thStyle, minWidth: 100 }}>Blend</th>
              <th style={{ ...thStyle, minWidth: 100 }}>Grain</th>
              <th style={{ ...thStyle, minWidth: 100 }}>Var/Type</th>
              <th style={{ ...thStyle, minWidth: 100 }}>Process</th>
              <th style={{ ...thStyle, minWidth: 60 }}>COO</th>
              <th style={{ ...thStyle, minWidth: 110 }}>Unit</th>
              <th style={{ ...thStyle, minWidth: 130 }}>Batch #</th>
              <th style={{ ...thStyle, minWidth: 140 }}>Expiry Date</th>
              
              {/* Dynamic warehouse columns */}
              {selectedWarehouses.map(warehouseId => (
                <th key={warehouseId} style={{ ...thStyle, minWidth: 120 }}>
                  {getWarehouseName(warehouseId)}
                </th>
              ))}
              
              {/* Warehouse Entry Button column (when no warehouses selected or as alternative) */}
              {selectedWarehouses.length === 0 && (
                <th style={{ ...thStyle, minWidth: 150 }}>Warehouses</th>
              )}
              
              <th style={{ ...thStyle, minWidth: 100, textAlign: "right" }}>Total Bags</th>
              <th style={{ ...thStyle, minWidth: 100, textAlign: "right" }}>Total MT</th>
              <th style={{ ...thStyle, minWidth: 110, textAlign: "right", color: "#228b22" }}>Empty MT</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((row, idx) => {
              const tb = rowTotalBags(row);
              const tm = rowTotalMt(row);
              const hasData = tb > 0;
              
              return (
                <tr
                  key={row.itemId}
                  style={{
                    borderBottom: "1px solid var(--line)",
                    background: hasData ? "rgba(59,91,219,0.03)" : undefined,
                  }}
                >
                  {/* Row number */}
                  <td style={{ padding: "10px", color: "var(--muted)", fontSize: "0.8rem", fontWeight: 600 }}>
                    {idx + 1}
                  </td>
                  
                  {/* Static columns */}
                  <td style={{ padding: "8px 10px" }}>
                    <span style={roCell}>{row.itemCode}</span>
                  </td>
                  <td style={{ padding: "8px 10px" }}>
                    <span style={{ ...roCell, maxWidth: 220, fontWeight: 600, color: "var(--ink)" }}>
                      {row.itemName}
                    </span>
                  </td>
                  <td style={{ padding: "8px 10px" }}>
                    <span style={roCell}>{row.barcode || "—"}</span>
                  </td>
                  <td style={{ padding: "8px 10px" }}>
                    <span style={roCell}>{row.blend || "—"}</span>
                  </td>
                  <td style={{ padding: "8px 10px" }}>
                    <span style={roCell}>{row.grainType || "—"}</span>
                  </td>
                  <td style={{ padding: "8px 10px" }}>
                    <span style={roCell}>{row.varietyType || "—"}</span>
                  </td>
                  <td style={{ padding: "8px 10px" }}>
                    <span style={roCell}>{row.processType || "—"}</span>
                  </td>
                  <td style={{ padding: "8px 10px" }}>
                    <span style={roCell}>{row.coo || "—"}</span>
                  </td>
                  <td style={{ padding: "8px 10px" }}>
                    <span style={roCell}>{row.unit || "—"}</span>
                  </td>
                  
                  {/* Editable columns */}
                  <td style={{ padding: "8px 10px" }}>
                    <input
                      style={inCell}
                      type="text"
                      value={row.batchNumber}
                      onChange={(e) => onRowUpdate(row.itemId, { batchNumber: e.target.value })}
                      placeholder="e.g. BATCH-001"
                    />
                  </td>
                  <td style={{ padding: "8px 10px" }}>
                    <input
                      style={inCell}
                      type="date"
                      value={row.expiryDate}
                      onChange={(e) => onRowUpdate(row.itemId, { expiryDate: e.target.value })}
                    />
                  </td>
                  
                  {/* Dynamic warehouse quantity columns */}
                  {selectedWarehouses.map(warehouseId => (
                    <td key={warehouseId} style={{ padding: "8px 10px" }}>
                      <input
                        style={numCell}
                        type="number"
                        min="0"
                        step="1"
                        value={row.warehouseBags[warehouseId] || ""}
                        onChange={(e) => {
                          const newBags = { ...row.warehouseBags, [warehouseId]: e.target.value };
                          onRowUpdate(row.itemId, { warehouseBags: newBags });
                        }}
                        placeholder="0"
                      />
                    </td>
                  ))}
                  
                  {/* Warehouse Entry Button (when no warehouses selected) */}
                  {selectedWarehouses.length === 0 && (
                    <td style={{ padding: "8px 10px" }}>
                      <button
                        type="button"
                        onClick={() => onOpenWarehouseModal(idx)}
                        style={{
                          padding: "9px 14px",
                          borderRadius: 6,
                          border: `1.5px solid ${BRAND}`,
                          background: tb > 0 ? "rgba(76,111,255,0.06)" : "#fff",
                          color: BRAND,
                          fontSize: "0.85rem",
                          fontWeight: 600,
                          cursor: "pointer",
                          display: "flex",
                          alignItems: "center",
                          gap: 6,
                          whiteSpace: "nowrap",
                          boxSizing: "border-box",
                          height: "38px",
                        }}
                      >
                        <svg
                          width="14"
                          height="14"
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          strokeWidth="2"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                        >
                          <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
                          <polyline points="9 22 9 12 15 12 15 22" />
                        </svg>
                        Enter Warehouses
                        {tb > 0 && (
                          <span
                            style={{
                              background: "var(--brand)",
                              color: "#fff",
                              borderRadius: 12,
                              padding: "2px 8px",
                              fontSize: "0.75rem",
                              fontWeight: 700,
                            }}
                          >
                            {countWarehousesWithQuantities(row)}
                          </span>
                        )}
                      </button>
                    </td>
                  )}
                  
                  {/* Total Bags (calculated) */}
                  <td style={{ padding: "8px 10px" }}>
                    <span
                      style={{
                        ...calcCell,
                        color: "var(--ink)",
                        background: hasData ? "#f0f4ff" : "#f4f7fd",
                        border: hasData ? "1px solid rgba(59,91,219,0.15)" : "1px solid var(--line)",
                      }}
                    >
                      {tb > 0 ? formatNumber(tb) : "—"}
                    </span>
                  </td>
                  
                  {/* Total MT (calculated or manual override) */}
                  <td style={{ padding: "8px 10px" }}>
                    {(() => {
                      if (row.bagWeightKg != null && row.bagWeightKg > 0) {
                        // Bag weight known — fully auto-calculated, read-only
                        return (
                          <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>
                        );
                      }
                      // Bag weight unknown (bagWeightKg is null) — show manual input with warning tooltip
                      return (
                        <div style={{ position: "relative" }}>
                          <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,
                              minWidth: 90,
                            }}
                            type="number"
                            min="0"
                            step="0.0001"
                            value={row.totalMtOverride}
                            placeholder="Enter MT"
                            onChange={(e) => onRowUpdate(row.itemId, { totalMtOverride: e.target.value })}
                            title="Bag weight not set for this item. Enter Total MT manually."
                          />
                          {row.totalMtOverride === "" && (
                            <span
                              style={{
                                position: "absolute",
                                top: -6,
                                right: -6,
                                width: 16,
                                height: 16,
                                borderRadius: "50%",
                                background: "#f0a500",
                                color: "#fff",
                                fontSize: "0.65rem",
                                fontWeight: 800,
                                display: "flex",
                                alignItems: "center",
                                justifyContent: "center",
                                cursor: "help",
                                lineHeight: 1,
                              }}
                              title="Bag weight not set for this item. Enter Total MT manually."
                            >
                              !
                            </span>
                          )}
                        </div>
                      );
                    })()}
                  </td>
                  
                  {/* Empty MT (calculated) */}
                  <td style={{ padding: "8px 10px" }}>
                    {hasData ? (() => {
                      const rowEmpty = Math.max(0, threshold - currentTotalMt - grandTotalMt);
                      const isLow = rowEmpty < 500;
                      return (
                        <span
                          style={{
                            ...calcCell,
                            color: isLow ? "var(--danger)" : "#228b22",
                            background: isLow ? "#fff5f5" : "#f0fff4",
                            border: `1px solid ${isLow ? "rgba(214,69,69,0.15)" : "rgba(34,139,34,0.15)"}`,
                          }}
                        >
                          {formatNumber(rowEmpty)}
                        </span>
                      );
                    })() : (
                      <span
                        style={{
                          ...calcCell,
                          background: "#f4f7fd",
                          border: "1px solid var(--line)",
                          color: "var(--muted)",
                        }}
                      >
                        —
                      </span>
                    )}
                  </td>
                </tr>
              );
            })}
            
            {/* Grand Total Row */}
            <tr style={{ background: "#f4f7fd", borderTop: "2px solid var(--line)" }}>
              <td
                colSpan={12 + selectedWarehouses.length + (selectedWarehouses.length === 0 ? 1 : 0)}
                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
                style={{
                  padding: "12px 10px",
                  textAlign: "right",
                  fontWeight: 800,
                  fontSize: "0.96rem",
                  color: totalEmpty < 500 ? "var(--danger)" : "#228b22",
                }}
              >
                {formatNumber(totalEmpty)}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  );
}

// Helper function to create a row from an item
export function makeRow(item: ItemRecord, warehouses: WarehouseRecord[]): SheetRow {
  const bags: Record<string, string> = {};
  warehouses.forEach((w) => { bags[w._id] = ""; });
  return {
    itemId: item._id,
    itemCode: item.itemCode,
    itemName: item.description ?? item.itemName ?? item.itemCode,
    barcode: item.barcode ?? "",
    blend: item.blend ?? "",
    grainType: item.grainType ?? "",
    varietyType: item.varietyType ?? "",
    processType: item.processType ?? "",
    coo: item.countryOfOrigin ?? "",
    unit: item.unit ?? (item.bagWeightKg ? `BAG/1x${item.bagWeightKg}kg` : ""),
    bagWeightKg: item.bagWeightKg ?? null,
    batchNumber: "",
    expiryDate: "",
    warehouseBags: bags,
    totalMtOverride: "",
  };
}
