"use client";

import React, { useState, useEffect } from "react";
import { getStockMovementSheets, getStockMovementSheet } from "@/lib/api";

/**
 * ExpiryReferenceModal Component
 * 
 * Read-only modal to view all expiry dates across inventory.
 * Shows items, batches, expiry dates, and available quantities.
 */

const BRAND = "#4c6fff";
const BRAND_GRADIENT = "linear-gradient(135deg, #4c6fff 0%, #5b7cff 100%)";

interface ExpiryRecord {
  itemCode: string;
  itemName: string;
  batchNumber: string;
  expiryDate: string;
  totalBags: number;
  totalMt: number;
  warehouses: string[];
}

interface ExpiryReferenceModalProps {
  isOpen: boolean;
  onClose: () => void;
}

export default function ExpiryReferenceModal({
  isOpen,
  onClose,
}: ExpiryReferenceModalProps) {
  const [loading, setLoading] = useState(false);
  const [expiryRecords, setExpiryRecords] = useState<ExpiryRecord[]>([]);
  const [searchQuery, setSearchQuery] = useState("");

  useEffect(() => {
    if (isOpen) {
      loadExpiryData();
    }
  }, [isOpen]);

  async function loadExpiryData() {
    setLoading(true);
    try {
      // Get all approved sheets
      const sheets = await getStockMovementSheets();
      const approvedSheets = sheets.filter((s) => s.approvalStatus === "approved");

      // Map to store aggregated expiry data
      const expiryMap = new Map<string, ExpiryRecord>();

      // Fetch each sheet with line items
      for (const sheet of approvedSheets) {
        try {
          const fullSheet = await getStockMovementSheet(sheet.id);

          for (const lineItem of fullSheet.lineItems ?? []) {
            if (!lineItem.expiryDate) continue;

            const itemCode = lineItem.itemCode ?? "Unknown";
            const itemName = lineItem.itemName || "-";
            const batchNumber = lineItem.batchNumber || "-";
            const expiryDate = lineItem.expiryDate;
            const key = `${itemCode}-${batchNumber}-${expiryDate}`;

            // Extract bag weight from unit field (e.g., "BAG/1x25kg" -> 25)
            const extractBagWeight = (unit: string | null): number => {
              if (!unit) return 25; // Default fallback
              const match = unit.match(/(\d+)x(\d+(?:\.\d+)?)kg/i);
              if (match) {
                return parseFloat(match[1]) * parseFloat(match[2]);
              }
              return 25; // Default fallback
            };

            const bagWeightKg = extractBagWeight(lineItem.unit);

            if (expiryMap.has(key)) {
              const existing = expiryMap.get(key)!;
              // Aggregate quantities
              Object.entries(lineItem.warehouseBags ?? {}).forEach(([wId, bags]) => {
                existing.totalBags += bags;
                if (!existing.warehouses.includes(wId)) {
                  existing.warehouses.push(wId);
                }
              });
              existing.totalMt = (existing.totalBags * bagWeightKg) / 1000;
            } else {
              const totalBags = Object.values(lineItem.warehouseBags ?? {}).reduce(
                (sum, bags) => sum + bags,
                0
              );
              const totalMt = (totalBags * bagWeightKg) / 1000;

              expiryMap.set(key, {
                itemCode,
                itemName,
                batchNumber,
                expiryDate,
                totalBags,
                totalMt,
                warehouses: Object.keys(lineItem.warehouseBags ?? {}),
              });
            }
          }
        } catch (err) {
          console.error(`Error fetching sheet ${sheet.id}:`, err);
        }
      }

      // Convert to array and sort by expiry date (earliest first)
      const records = Array.from(expiryMap.values()).sort((a, b) => {
        return new Date(a.expiryDate).getTime() - new Date(b.expiryDate).getTime();
      });

      setExpiryRecords(records);
    } catch (err) {
      console.error("Error loading expiry data:", err);
    } finally {
      setLoading(false);
    }
  }

  // Filter records based on search
  const filteredRecords = expiryRecords.filter((record) => {
    const searchLower = searchQuery.toLowerCase();
    return (
      !searchQuery ||
      record.itemCode.toLowerCase().includes(searchLower) ||
      record.itemName.toLowerCase().includes(searchLower) ||
      record.batchNumber.toLowerCase().includes(searchLower)
    );
  });

  // Handle Escape key
  useEffect(() => {
    function handleEscape(e: KeyboardEvent) {
      if (e.key === "Escape" && isOpen) {
        onClose();
      }
    }

    document.addEventListener("keydown", handleEscape);
    return () => document.removeEventListener("keydown", handleEscape);
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  return (
    <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={onClose}
    >
      <div
        style={{
          background: "#fff",
          borderRadius: 16,
          maxWidth: "1200px",
          width: "100%",
          maxHeight: "90vh",
          border: "1.5px solid rgba(76, 111, 255, 0.25)",
          boxShadow: "0 24px 64px rgba(15,22,48,0.22)",
          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",
              }}
            >
              📅 Expiry Reference
            </h2>
            <p
              style={{
                margin: "4px 0 0",
                fontSize: "0.84rem",
                color: "rgba(255,255,255,0.82)",
              }}
            >
              View all batch expiry dates across inventory
            </p>
          </div>
          <button
            type="button"
            onClick={onClose}
            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>

        {/* Search Bar */}
        <div style={{ padding: "20px 26px", borderBottom: "1px solid rgba(0,0,0,0.07)" }}>
          <input
            type="text"
            placeholder="Search by item code, item name, or batch number..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            style={{
              width: "100%",
              padding: "10px 14px",
              borderRadius: 8,
              border: "1.5px solid var(--line)",
              fontSize: "0.88rem",
              fontFamily: "inherit",
              color: "var(--ink)",
              outline: "none",
              boxSizing: "border-box",
            }}
          />
        </div>

        {/* Modal Body */}
        <div style={{ flex: 1, overflowY: "auto", padding: "20px 26px" }}>
          {loading ? (
            <div style={{ textAlign: "center", padding: "40px", color: "var(--muted)" }}>
              <div
                style={{
                  display: "inline-block",
                  width: 32,
                  height: 32,
                  border: "3px solid rgba(76,111,255,0.2)",
                  borderTopColor: BRAND,
                  borderRadius: "50%",
                  animation: "spin 0.8s linear infinite",
                }}
              />
              <p style={{ marginTop: 16 }}>Loading expiry data...</p>
            </div>
          ) : filteredRecords.length === 0 ? (
            <div style={{ textAlign: "center", padding: "40px", color: "var(--muted)" }}>
              <p style={{ fontSize: "1.1rem", marginBottom: 8 }}>
                {searchQuery ? "No matching records found" : "No expiry data available"}
              </p>
              <p style={{ fontSize: "0.86rem" }}>
                {searchQuery
                  ? "Try a different search term"
                  : "Expiry data will appear here once stock-in sheets are approved"}
              </p>
            </div>
          ) : (
            <div style={{ overflowX: "auto" }}>
              <table style={{ borderCollapse: "collapse", width: "100%", minWidth: "800px" }}>
                <thead>
                  <tr>
                    <th
                      style={{
                        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",
                      }}
                    >
                      Item Code
                    </th>
                    <th
                      style={{
                        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",
                      }}
                    >
                      Item Name
                    </th>
                    <th
                      style={{
                        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",
                      }}
                    >
                      Batch Number
                    </th>
                    <th
                      style={{
                        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",
                      }}
                    >
                      Expiry Date
                    </th>
                    <th
                      style={{
                        padding: "12px 10px",
                        textAlign: "right",
                        color: "var(--muted)",
                        fontSize: "0.75rem",
                        textTransform: "uppercase",
                        letterSpacing: "0.06em",
                        whiteSpace: "nowrap",
                        borderBottom: "2px solid var(--line)",
                        background: "#f4f7fd",
                      }}
                    >
                      Total Bags
                    </th>
                    <th
                      style={{
                        padding: "12px 10px",
                        textAlign: "right",
                        color: "var(--muted)",
                        fontSize: "0.75rem",
                        textTransform: "uppercase",
                        letterSpacing: "0.06em",
                        whiteSpace: "nowrap",
                        borderBottom: "2px solid var(--line)",
                        background: "#f4f7fd",
                      }}
                    >
                      Total MT
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {filteredRecords.map((record, idx) => {
                    const expiryDate = new Date(record.expiryDate);
                    const today = new Date();
                    const daysUntilExpiry = Math.floor(
                      (expiryDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24)
                    );
                    const isExpiringSoon = daysUntilExpiry <= 30 && daysUntilExpiry >= 0;
                    const isExpired = daysUntilExpiry < 0;

                    return (
                      <tr
                        key={idx}
                        style={{
                          borderBottom: "1px solid var(--line)",
                          background: isExpired
                            ? "#fff5f5"
                            : isExpiringSoon
                            ? "#fffbf0"
                            : idx % 2 === 0
                            ? "#fff"
                            : "#fafbff",
                        }}
                      >
                        <td
                          style={{
                            padding: "10px",
                            fontSize: "0.84rem",
                            fontFamily: "monospace",
                            fontWeight: 600,
                            color: "var(--ink)",
                          }}
                        >
                          {record.itemCode}
                        </td>
                        <td style={{ padding: "10px", fontSize: "0.84rem", color: "var(--ink)" }}>
                          {record.itemName}
                        </td>
                        <td
                          style={{
                            padding: "10px",
                            fontSize: "0.84rem",
                            fontFamily: "monospace",
                            color: "var(--muted)",
                          }}
                        >
                          {record.batchNumber}
                        </td>
                        <td style={{ padding: "10px", fontSize: "0.84rem" }}>
                          <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                            <span
                              style={{
                                color: isExpired ? "#d64545" : isExpiringSoon ? "#f59e0b" : "var(--ink)",
                                fontWeight: isExpired || isExpiringSoon ? 600 : 400,
                              }}
                            >
                              {expiryDate.toLocaleDateString("en-AE")}
                            </span>
                            {isExpired && (
                              <span
                                style={{
                                  fontSize: "0.7rem",
                                  color: "#d64545",
                                  background: "rgba(214,69,69,0.1)",
                                  padding: "2px 6px",
                                  borderRadius: 4,
                                  fontWeight: 600,
                                }}
                              >
                                EXPIRED
                              </span>
                            )}
                            {isExpiringSoon && !isExpired && (
                              <span
                                style={{
                                  fontSize: "0.7rem",
                                  color: "#f59e0b",
                                  background: "rgba(245,158,11,0.1)",
                                  padding: "2px 6px",
                                  borderRadius: 4,
                                  fontWeight: 600,
                                }}
                              >
                                {daysUntilExpiry}d left
                              </span>
                            )}
                          </div>
                        </td>
                        <td
                          style={{
                            padding: "10px",
                            fontSize: "0.84rem",
                            textAlign: "right",
                            fontFamily: "monospace",
                            color: "var(--ink)",
                          }}
                        >
                          {record.totalBags.toLocaleString()}
                        </td>
                        <td
                          style={{
                            padding: "10px",
                            fontSize: "0.84rem",
                            textAlign: "right",
                            fontFamily: "monospace",
                            fontWeight: 600,
                            color: "var(--brand)",
                          }}
                        >
                          {record.totalMt.toFixed(2)}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* Modal Footer */}
        <div
          style={{
            padding: "16px 26px",
            borderTop: "1px solid rgba(0,0,0,0.07)",
            background: "#f8f9fb",
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
          }}
        >
          <div style={{ fontSize: "0.84rem", color: "var(--muted)" }}>
            Showing {filteredRecords.length} of {expiryRecords.length} records
          </div>
          <button
            type="button"
            onClick={onClose}
            style={{
              padding: "10px 22px",
              borderRadius: 8,
              border: "1.5px solid rgba(0,0,0,0.12)",
              background: "#fff",
              color: "#495057",
              fontSize: "0.88rem",
              fontWeight: 600,
              cursor: "pointer",
            }}
          >
            Close
          </button>
        </div>
      </div>

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