"use client";

import React, { useState, useCallback, useEffect } from "react";

/* ------------------------------------------------------------------ */
/* Types                                                               */
/* ------------------------------------------------------------------ */

interface SimpleKeypadModalProps {
  open: boolean;
  onClose: () => void;
  onConfirm: (qty: number) => void;
  maxQty: number;
  itemName: string;
  initialQty?: number;
}

/* ------------------------------------------------------------------ */
/* Numpad Keys                                                         */
/* ------------------------------------------------------------------ */

const KEYS = [
  { label: "7", action: "7" },
  { label: "8", action: "8" },
  { label: "9", action: "9" },
  { label: "\u2190", action: "backspace" },
  { label: "4", action: "4" },
  { label: "5", action: "5" },
  { label: "6", action: "6" },
  { label: "C", action: "clear" },
  { label: "1", action: "1" },
  { label: "2", action: "2" },
  { label: "3", action: "3" },
  { label: "MAX", action: "max" },
];

/* ------------------------------------------------------------------ */
/* Component                                                           */
/* ------------------------------------------------------------------ */

export function SimpleKeypadModal({
  open,
  onClose,
  onConfirm,
  maxQty,
  itemName,
  initialQty,
}: SimpleKeypadModalProps) {
  const [qty, setQty] = useState("0");

  /* Reset on open */
  useEffect(() => {
    if (open) {
      setQty(initialQty !== undefined && initialQty > 0 ? String(initialQty) : "0");
    }
  }, [open, initialQty]);

  const qtyNum = parseInt(qty, 10) || 0;
  const isOverMax = qtyNum > maxQty;

  /* Numpad input handler */
  const handleInput = useCallback(
    (key: string) => {
      setQty((prev) => {
        switch (key) {
          case "backspace":
            return prev.length <= 1 ? "0" : prev.slice(0, -1);
          case "clear":
            return "0";
          case "max":
            return String(maxQty);
          default: {
            const next = prev === "0" ? key : prev + key;
            const num = parseInt(next, 10);
            if (isNaN(num)) return prev;
            return next;
          }
        }
      });
    },
    [maxQty],
  );

  const handleConfirm = () => {
    if (qtyNum <= 0) return;
    const finalQty = Math.min(qtyNum, maxQty);
    onConfirm(finalQty);
    onClose();
  };

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      {/* Overlay */}
      <div className="absolute inset-0 bg-black/40" onClick={onClose} />

      {/* Panel */}
      <div className="relative bg-white w-[90%] max-w-[360px] rounded-2xl shadow-2xl z-10 overflow-hidden">
        {/* Header - blue gradient */}
        <div
          className="flex items-center justify-between px-4 py-3"
          style={{ background: "linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)" }}
        >
          <span className="text-[13px] text-white/90 bg-white/20 px-3 py-1 rounded-full">
            {maxQty.toLocaleString()} EA
          </span>
          <button
            onClick={onClose}
            className="w-8 h-8 rounded-lg bg-white/20 flex items-center justify-center text-white hover:bg-white/30 active:scale-95 transition-all"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        {/* Body */}
        <div className="p-4">
          <p className="text-center text-sm font-semibold text-gray-700 mb-1">
            수량 입력
          </p>
          <p className="text-center text-xs text-gray-400 mb-3 truncate px-2">
            {itemName}
          </p>

          {/* Display */}
          <input
            type="text"
            readOnly
            value={qtyNum.toLocaleString()}
            className={`w-full px-4 py-3 text-right text-3xl font-bold border-2 rounded-xl bg-gray-50 mb-3 ${
              isOverMax ? "border-red-300 text-red-500" : "border-gray-200 text-gray-900"
            }`}
            style={{ fontVariantNumeric: "tabular-nums" }}
          />

          {isOverMax && (
            <p className="text-center text-xs text-red-500 font-medium mb-2">
              {maxQty.toLocaleString()}EA ({maxQty.toLocaleString()}EA)
            </p>
          )}

          {/* Numpad grid: 4x3 + bottom row */}
          <div className="grid grid-cols-4 gap-2.5">
            {KEYS.map((key) => (
              <button
                key={key.action}
                onClick={() => handleInput(key.action)}
                className={`h-14 rounded-xl text-lg font-semibold active:scale-95 transition-all ${
                  key.action === "backspace" || key.action === "clear"
                    ? "bg-amber-100 text-amber-700 hover:bg-amber-200"
                    : key.action === "max"
                    ? "bg-blue-100 text-blue-700 hover:bg-blue-200 text-sm"
                    : "bg-gray-100 text-gray-900 hover:bg-gray-200"
                }`}
              >
                {key.label}
              </button>
            ))}

            {/* Bottom row: 0 (span 2) + Confirm (span 2) */}
            <button
              onClick={() => handleInput("0")}
              className="col-span-2 h-14 rounded-xl text-lg font-semibold bg-gray-100 text-gray-900 hover:bg-gray-200 active:scale-95 transition-all"
            >
              0
            </button>
            <button
              onClick={handleConfirm}
              disabled={qtyNum <= 0}
              className={`col-span-2 h-14 rounded-xl text-lg font-bold text-white active:scale-95 transition-all ${
                qtyNum <= 0 ? "opacity-40 cursor-not-allowed" : ""
              }`}
              style={{
                background: qtyNum <= 0
                  ? "#9ca3af"
                  : "linear-gradient(135deg, #10b981 0%, #059669 100%)",
              }}
            >
              확인
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
