"use client";

import React, { useState, useEffect, useRef } from "react";
import type { WarehouseRecord } from "@/lib/api";

/**
 * WarehouseEntryModal Component
 *
 * A modal dialog for focused warehouse quantity entry on the Stock In page.
 * Displays all warehouses in a vertical list for better readability and accessibility.
 *
 * Features:
 * - Vertical warehouse list (no horizontal scrolling)
 * - Keyboard navigation (Tab, Shift+Tab, Enter, Escape)
 * - Copy from previous batch functionality
 * - Apply to all warehouses shortcut
 */

// Brand blue matching the active sidebar nav item
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)";

// SheetRow interface matches the structure from page.tsx
interface SheetRow {
  itemId: string;
  itemCode: string;
  itemName: string;
  barcode: string;
  blend: string;
  grainType: string;
  varietyType: string;
  processType: string;
  coo: string;
  unit: string;
  batchNumber: string;
  expiryDate: string;
  warehouseBags: Record<string, string>;
  totalMtOverride: string;
}

interface WarehouseEntryModalProps {
  warehouses: WarehouseRecord[];
  currentRow: SheetRow;
  previousRow: SheetRow | null;
  onSave: (quantities: Record<string, string>) => void;
  onClose: () => void;
}

export default function WarehouseEntryModal({
  warehouses,
  currentRow,
  previousRow,
  onSave,
  onClose,
}: WarehouseEntryModalProps) {
  const [localQuantities, setLocalQuantities] = useState<Record<string, string>>({});
  const [focusedIndex, setFocusedIndex] = useState<number>(0);
  const inputRefs = useRef<(HTMLInputElement | null)[]>([]);
  const [feedbackMessage, setFeedbackMessage] = useState<string>("");

  useEffect(() => {
    setLocalQuantities({ ...currentRow.warehouseBags });
    setFocusedIndex(0);
    setTimeout(() => inputRefs.current[0]?.focus(), 50);
  }, [currentRow]);

  useEffect(() => {
    if (feedbackMessage) {
      const timer = setTimeout(() => setFeedbackMessage(""), 2000);
      return () => clearTimeout(timer);
    }
  }, [feedbackMessage]);

  function validateQuantity(value: string): boolean {
    if (value === "") return true;
    const num = Number(value);
    return !isNaN(num) && num >= 0 && Number.isInteger(num);
  }

  function updateQuantity(warehouseId: string, value: string) {
    if (!validateQuantity(value)) return;
    setLocalQuantities(prev => ({ ...prev, [warehouseId]: value }));
  }

  function copyFromPrevious() {
    if (!previousRow) return;
    setLocalQuantities({ ...previousRow.warehouseBags });
    setFeedbackMessage("Copied from previous batch");
  }

  function applyToAll(value: string) {
    if (!validateQuantity(value)) return;
    const updated: Record<string, string> = {};
    warehouses.forEach(w => { updated[w._id] = value; });
    setLocalQuantities(updated);
    setFeedbackMessage(`Applied "${value || "0"}" to all warehouses`);
  }

  function handleSave() {
    onSave(localQuantities);
    onClose();
  }

  function handleKeyDown(e: React.KeyboardEvent, index: number) {
    if (e.key === "Tab" && !e.shiftKey) {
      e.preventDefault();
      const nextIndex = index + 1;
      if (nextIndex < warehouses.length) {
        setFocusedIndex(nextIndex);
        inputRefs.current[nextIndex]?.focus();
      } else {
        document.getElementById("modal-save-btn")?.focus();
      }
    } else if (e.key === "Tab" && e.shiftKey) {
      e.preventDefault();
      const prevIndex = index - 1;
      if (prevIndex >= 0) {
        setFocusedIndex(prevIndex);
        inputRefs.current[prevIndex]?.focus();
      }
    } else if (e.key === "Enter") {
      e.preventDefault();
      handleSave();
    } else if (e.key === "Escape") {
      e.preventDefault();
      onClose();
    }
  }

  const hasValue = (id: string) =>
    !!localQuantities[id] && Number(localQuantities[id]) > 0;

  return (
    <div
      style={{
        position: "fixed",
        inset: 0,
        zIndex: 1000,
        background: "rgba(0,0,0,0.6)",
        backdropFilter: "blur(4px)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
      }}
      onClick={onClose}
    >
      <div
        style={{
          background: "#fff",
          borderRadius: 16,
          maxWidth: 640,
          width: "95%",
          /* ── border requested by user ── */
          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)",
          position: "relative",
          maxHeight: "90vh",
          display: "flex",
          flexDirection: "column",
          overflow: "hidden",
        }}
        onClick={e => e.stopPropagation()}
      >
        {/* ── Header ─────────────────────────────────────────────────────── */}
        <div
          style={{
            padding: "22px 26px 20px",
            borderBottom: "1px solid rgba(76,111,255,0.12)",
            background: BRAND_GRADIENT,
          }}
        >
          {/* Title row */}
          <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 10 }}>
            {/* SVG warehouse icon — replaces emoji */}
            <div
              style={{
                width: 42,
                height: 42,
                borderRadius: 10,
                background: "rgba(255,255,255,0.18)",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                flexShrink: 0,
              }}
            >
              <svg
                width="22"
                height="22"
                viewBox="0 0 24 24"
                fill="none"
                stroke="#fff"
                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>
            </div>

            <div style={{ flex: 1, minWidth: 0 }}>
              <h3
                style={{
                  margin: 0,
                  fontSize: "1.15rem",
                  fontWeight: 700,
                  color: "#fff",
                  letterSpacing: "-0.02em",
                  whiteSpace: "nowrap",
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                }}
              >
                Warehouse Quantities
              </h3>
              <p
                style={{
                  margin: "3px 0 0",
                  fontSize: "0.84rem",
                  color: "rgba(255,255,255,0.82)",
                  whiteSpace: "nowrap",
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                }}
              >
                {currentRow.itemName}
              </p>
            </div>
          </div>

          {/* Batch pill */}
          {currentRow.batchNumber && (
            <div
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: 6,
                padding: "3px 10px",
                borderRadius: 999,
                background: "rgba(255,255,255,0.18)",
                fontSize: "0.78rem",
                color: "#fff",
                fontWeight: 600,
                marginBottom: 14,
              }}
            >
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <rect x="3" y="4" width="18" height="18" rx="2" ry="2" />
                <line x1="16" y1="2" x2="16" y2="6" />
                <line x1="8" y1="2" x2="8" y2="6" />
                <line x1="3" y1="10" x2="21" y2="10" />
              </svg>
              <span style={{ opacity: 0.8 }}>Batch:</span>
              <span>{currentRow.batchNumber}</span>
            </div>
          )}

          {/* Action buttons */}
          <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
            {/* Copy from Previous */}
            <button
              type="button"
              onClick={copyFromPrevious}
              disabled={!previousRow}
              title={previousRow ? "Copy quantities from previous batch" : "No previous batch available"}
              style={{
                padding: "9px 15px",
                borderRadius: 8,
                border: "none",
                background: previousRow ? "rgba(255,255,255,0.95)" : "rgba(255,255,255,0.28)",
                color: previousRow ? BRAND : "rgba(255,255,255,0.55)",
                fontSize: "0.84rem",
                fontWeight: 600,
                cursor: previousRow ? "pointer" : "not-allowed",
                display: "flex",
                alignItems: "center",
                gap: 7,
                boxShadow: previousRow ? "0 2px 8px rgba(0,0,0,0.12)" : "none",
              }}
            >
              {/* Clipboard copy SVG */}
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <rect x="9" y="9" width="13" height="13" rx="2" ry="2" />
                <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
              </svg>
              Copy from Previous
            </button>

            {/* Apply to All */}
            <button
              type="button"
              onClick={() => {
                const firstValue = Object.values(localQuantities).find(v => v !== "") || "";
                const valueToApply = prompt("Enter value to apply to all warehouses:", firstValue);
                if (valueToApply !== null) applyToAll(valueToApply);
              }}
              title="Apply one value to all warehouses"
              style={{
                padding: "9px 15px",
                borderRadius: 8,
                border: "none",
                background: "rgba(255,255,255,0.95)",
                color: BRAND,
                fontSize: "0.84rem",
                fontWeight: 600,
                cursor: "pointer",
                display: "flex",
                alignItems: "center",
                gap: 7,
                boxShadow: "0 2px 8px rgba(0,0,0,0.12)",
              }}
            >
              {/* Layers / apply-all SVG */}
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <polygon points="12 2 2 7 12 12 22 7 12 2" />
                <polyline points="2 17 12 22 22 17" />
                <polyline points="2 12 12 17 22 12" />
              </svg>
              Apply to All
            </button>
          </div>

          {/* Feedback toast */}
          {feedbackMessage && (
            <div
              style={{
                marginTop: 12,
                padding: "9px 13px",
                borderRadius: 8,
                background: "rgba(255,255,255,0.95)",
                color: "#16a34a",
                fontSize: "0.83rem",
                fontWeight: 600,
                display: "flex",
                alignItems: "center",
                gap: 7,
              }}
            >
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <polyline points="20 6 9 17 4 12" />
              </svg>
              {feedbackMessage}
            </div>
          )}
        </div>

        {/* ── Warehouse list ──────────────────────────────────────────────── */}
        <div
          style={{
            padding: "20px 26px",
            overflowY: "auto",
            flex: 1,
          }}
        >
          {warehouses.map((warehouse, index) => {
            const active = hasValue(warehouse._id);
            return (
              <div
                key={warehouse._id}
                style={{
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "space-between",
                  marginBottom: 10,
                  gap: 16,
                  padding: "10px 14px",
                  borderRadius: 10,
                  background: active ? "rgba(76,111,255,0.06)" : "#f8f9fb",
                  border: active
                    ? `1.5px solid rgba(76,111,255,0.28)`
                    : "1.5px solid rgba(0,0,0,0.06)",
                  transition: "all 0.15s ease",
                }}
              >
                {/* Icon + label */}
                <div style={{ display: "flex", alignItems: "center", gap: 11, flex: 1, minWidth: 0 }}>
                  <div
                    style={{
                      width: 34,
                      height: 34,
                      borderRadius: 8,
                      background: active ? BRAND_GRADIENT : "#e9ecef",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      flexShrink: 0,
                    }}
                  >
                    {/* Warehouse building SVG */}
                    <svg
                      width="17"
                      height="17"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke={active ? "#fff" : "#868e96"}
                      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>
                  </div>
                  <label
                    htmlFor={`warehouse-${warehouse._id}`}
                    style={{
                      fontSize: "0.9rem",
                      fontWeight: 600,
                      color: active ? "#1a202c" : "#495057",
                      cursor: "pointer",
                      whiteSpace: "nowrap",
                      overflow: "hidden",
                      textOverflow: "ellipsis",
                    }}
                  >
                    {warehouse.name}
                  </label>
                </div>

                {/* Quantity input */}
                <input
                  id={`warehouse-${warehouse._id}`}
                  ref={el => { inputRefs.current[index] = el; }}
                  type="number"
                  min="0"
                  step="1"
                  value={localQuantities[warehouse._id] ?? ""}
                  onChange={e => updateQuantity(warehouse._id, e.target.value)}
                  onKeyDown={e => handleKeyDown(e, index)}
                  placeholder="0"
                  style={{
                    padding: "10px 14px",
                    borderRadius: 8,
                    border: active ? `2px solid ${BRAND}` : "2px solid rgba(0,0,0,0.1)",
                    background: "#fff",
                    fontSize: "0.92rem",
                    fontFamily: "inherit",
                    fontWeight: 600,
                    color: active ? BRAND : "#495057",
                    outline: "none",
                    width: 120,
                    textAlign: "right",
                    boxSizing: "border-box",
                    transition: "border-color 0.15s ease, color 0.15s ease",
                    minWidth: "unset",
                  } as React.CSSProperties}
                />
              </div>
            );
          })}
        </div>

        {/* ── 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={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",
            }}
          >
            Cancel
          </button>
          <button
            id="modal-save-btn"
            type="button"
            onClick={() => { onSave(localQuantities); onClose(); }}
            onKeyDown={e => {
              if (e.key === "Enter") { e.preventDefault(); handleSave(); }
              else if (e.key === "Escape") { e.preventDefault(); onClose(); }
            }}
            style={{
              padding: "10px 22px",
              borderRadius: 8,
              border: "none",
              background: BRAND_GRADIENT,
              color: "#fff",
              fontSize: "0.88rem",
              fontWeight: 600,
              cursor: "pointer",
              boxShadow: BRAND_SHADOW,
              display: "flex",
              alignItems: "center",
              gap: 8,
            }}
          >
            {/* Checkmark SVG */}
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
              <polyline points="20 6 9 17 4 12" />
            </svg>
            Save Changes
          </button>
        </div>
      </div>
    </div>
  );
}
