"use client";

import React, { useState, useCallback, useEffect } from "react";
import type { PackageUnit } from "./PackagingModal";
import { getPkgUnitsByItem, type PkgUnitByItem } from "@/lib/api/packaging";

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

export interface PackageEntry {
  unit: PackageUnit;
  count: number;
  qtyPerUnit: number;
}

export interface LoadingUnitSelection {
  loading_code: string;
  loading_name: string;
  loading_type: string;
  max_load_qty: number;
}

interface NumberPadModalProps {
  open: boolean;
  onClose: () => void;
  onConfirm: (qty: number, packages: PackageEntry[]) => void;
  maxQty: number;
  itemName: string;
  itemNumber?: string;
  initialPackages?: PackageEntry[];
}

type Step = "list" | "packaging" | "count";

/* ------------------------------------------------------------------ */
/* 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 NumberPadModal({
  open,
  onClose,
  onConfirm,
  maxQty,
  itemName,
  itemNumber,
  initialPackages,
}: NumberPadModalProps) {
  const [step, setStep] = useState<Step>("list");
  const [packages, setPackages] = useState<PackageEntry[]>([]);
  const [packageUnits, setPackageUnits] = useState<PackageUnit[]>([]);
  const [pkgLoading, setPkgLoading] = useState(false);

  const [selectedUnit, setSelectedUnit] = useState<PackageUnit | null>(null);
  const [count, setCount] = useState("0");
  const [editingIndex, setEditingIndex] = useState<number | null>(null);

  /* Fetch packaging units from DB */
  useEffect(() => {
    if (!open || !itemNumber) {
      setPackageUnits([]);
      return;
    }
    let cancelled = false;
    setPkgLoading(true);
    getPkgUnitsByItem(itemNumber)
      .then((res) => {
        if (cancelled) return;
        setPackageUnits(
          res.data.map((pu: PkgUnitByItem) => ({
            label: pu.pkg_name,
            icon: "\uD83D\uDCE6",
            value: pu.pkg_code,
            pkg_qty: pu.pkg_qty,
          }))
        );
      })
      .catch(() => {
        if (!cancelled) setPackageUnits([]);
      })
      .finally(() => {
        if (!cancelled) setPkgLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, [open, itemNumber]);

  /* Reset on open */
  useEffect(() => {
    if (open) {
      setPackages(initialPackages ? [...initialPackages] : []);
      setStep("list");
      setSelectedUnit(null);
      setCount("0");
      setEditingIndex(null);
    }
  }, [open, initialPackages]);

  /* Computed values */
  const totalPackagedQty = packages.reduce(
    (s, p) => s + p.count * p.qtyPerUnit,
    0
  );
  const unpackedQty = Math.max(0, maxQty - totalPackagedQty);
  const countNum = parseInt(count, 10) || 0;

  /* 편집 중이면 해당 행 수량만큼은 "사용 가능"으로 되돌려줌 */
  const editingEntry =
    editingIndex !== null ? packages[editingIndex] ?? null : null;
  const editingReservedQty = editingEntry
    ? editingEntry.count * editingEntry.qtyPerUnit
    : 0;
  const availableForCurrent = unpackedQty + editingReservedQty;
  const currentPkgQty = selectedUnit?.pkg_qty ?? 0;
  const maxCountForCurrent =
    currentPkgQty > 0 ? Math.floor(availableForCurrent / currentPkgQty) : 0;

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

  /* Step handlers */
  const openAddFlow = () => {
    setEditingIndex(null);
    setSelectedUnit(null);
    setCount("0");
    setStep("packaging");
  };

  const openEditFlow = (idx: number) => {
    const entry = packages[idx];
    if (!entry) return;
    setEditingIndex(idx);
    setSelectedUnit(entry.unit);
    setCount(String(entry.count));
    setStep("count");
  };

  const handleSelectUnit = (unit: PackageUnit) => {
    setSelectedUnit(unit);
    setCount("0");
    setStep("count");
  };

  const handleCountConfirm = () => {
    if (!selectedUnit || countNum <= 0) return;
    const qtyPerUnit = selectedUnit.pkg_qty ?? 0;
    setPackages((prev) => {
      if (editingIndex !== null) {
        return prev.map((p, i) =>
          i === editingIndex ? { ...p, count: countNum, qtyPerUnit } : p
        );
      }
      const existing = prev.findIndex(
        (p) => p.unit.value === selectedUnit.value
      );
      if (existing >= 0) {
        return prev.map((p, i) =>
          i === existing ? { ...p, count: p.count + countNum } : p
        );
      }
      return [...prev, { unit: selectedUnit, count: countNum, qtyPerUnit }];
    });
    setStep("list");
    setSelectedUnit(null);
    setCount("0");
    setEditingIndex(null);
  };

  const handleDelete = (idx: number) => {
    setPackages((prev) => prev.filter((_, i) => i !== idx));
  };

  const handleBack = () => {
    if (step === "count") {
      if (editingIndex !== null) {
        setStep("list");
        setSelectedUnit(null);
        setCount("0");
        setEditingIndex(null);
      } else {
        setStep("packaging");
        setSelectedUnit(null);
        setCount("0");
      }
    } else if (step === "packaging") {
      setStep("list");
    }
  };

  const handleFinalConfirm = () => {
    if (packages.length === 0) return;
    const finalQty = Math.min(totalPackagedQty, maxQty);
    onConfirm(finalQty, packages);
    onClose();
  };

  if (!open) return null;

  /* ------------------------------------------------------------------ */
  /* Render helpers                                                      */
  /* ------------------------------------------------------------------ */

  const renderNumpad = (
    currentValue: string,
    onKey: (key: string) => void,
    onConfirmStep: () => void,
    confirmLabel: string,
    confirmDisabled: boolean
  ) => (
    <>
      <input
        type="text"
        readOnly
        value={parseInt(currentValue, 10).toLocaleString()}
        className="w-full px-4 py-3 text-right text-3xl font-bold border-2 border-gray-200 rounded-xl bg-gray-50 text-gray-900 mb-3"
        style={{ fontVariantNumeric: "tabular-nums" }}
      />
      <div className="grid grid-cols-4 gap-2.5">
        {KEYS.map((key) => (
          <button
            key={key.action}
            onClick={() => onKey(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>
        ))}
        <button
          onClick={() => onKey("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={onConfirmStep}
          disabled={confirmDisabled}
          className={`col-span-2 h-14 rounded-xl text-lg font-bold text-white active:scale-95 transition-all ${
            confirmDisabled ? "opacity-40 cursor-not-allowed" : ""
          }`}
          style={{
            background: confirmDisabled
              ? "#9ca3af"
              : "linear-gradient(135deg, #10b981 0%, #059669 100%)",
          }}
        >
          {confirmLabel}
        </button>
      </div>
    </>
  );

  const renderPackagingGrid = (onSelect: (unit: PackageUnit) => void) => (
    <>
      {pkgLoading ? (
        <div className="flex items-center justify-center py-8">
          <div className="w-6 h-6 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" />
          <span className="ml-2 text-sm text-gray-500">불러오는 중...</span>
        </div>
      ) : packageUnits.length === 0 ? (
        <div className="text-center py-8 text-sm text-gray-400">
          등록된 포장단위가 없습니다
        </div>
      ) : (
        <div className="grid grid-cols-3 gap-3">
          {packageUnits.map((unit) => (
            <button
              key={unit.value}
              onClick={() => onSelect(unit)}
              className="flex flex-col items-center gap-2 py-4 px-3 border-2 border-gray-200 rounded-xl bg-white text-sm font-medium text-gray-700 hover:border-blue-400 hover:bg-blue-50 active:scale-95 transition-all min-h-[80px]"
            >
              <span className="text-2xl">{unit.icon}</span>
              <span className="text-center leading-tight">{unit.label}</span>
              {unit.pkg_qty && unit.pkg_qty > 0 && (
                <span className="text-[10px] text-gray-400">
                  {unit.pkg_qty}EA/개
                </span>
              )}
            </button>
          ))}
        </div>
      )}
    </>
  );

  /* Header: 단계별 색상 */
  const headerBg =
    step === "count" && editingIndex !== null
      ? "linear-gradient(135deg, #8b5cf6 0%, #6d28d9 100%)"
      : "linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)";

  const headerBadge =
    step === "count" && editingIndex !== null
      ? "수정"
      : `최대 ${maxQty.toLocaleString()} EA`;

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

      <div className="relative bg-white w-[90%] max-w-[420px] rounded-2xl shadow-2xl z-10 overflow-hidden">
        {/* Header */}
        <div
          className="flex items-center justify-between px-4 py-3"
          style={{ background: headerBg }}
        >
          <div className="flex items-center gap-2">
            {step !== "list" && (
              <button
                onClick={handleBack}
                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="M15.75 19.5L8.25 12l7.5-7.5"
                  />
                </svg>
              </button>
            )}
            <span className="text-[13px] text-white/90 bg-white/20 px-3 py-1 rounded-full">
              {headerBadge}
            </span>
          </div>
          <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">
          {/* ====== LIST: 목록 + 추가 + 확인 ====== */}
          {step === "list" && (
            <>
              {/* 요약 (포장 수량 / 미포장 잔량) */}
              <div className="grid grid-cols-2 gap-2 mb-3">
                <div className="bg-blue-50 border border-blue-200 rounded-lg px-3 py-2">
                  <p className="text-[10px] text-blue-600 font-semibold">
                    포장 수량
                  </p>
                  <p
                    className="text-lg font-black text-blue-700"
                    style={{ fontVariantNumeric: "tabular-nums" }}
                  >
                    {totalPackagedQty.toLocaleString()} EA
                  </p>
                </div>
                <div
                  className={`border rounded-lg px-3 py-2 ${
                    unpackedQty > 0
                      ? "bg-amber-50 border-amber-200"
                      : "bg-green-50 border-green-200"
                  }`}
                >
                  <p
                    className={`text-[10px] font-semibold ${
                      unpackedQty > 0 ? "text-amber-600" : "text-green-600"
                    }`}
                  >
                    미포장
                  </p>
                  <p
                    className={`text-lg font-black ${
                      unpackedQty > 0 ? "text-amber-700" : "text-green-700"
                    }`}
                    style={{ fontVariantNumeric: "tabular-nums" }}
                  >
                    {unpackedQty.toLocaleString()} EA
                  </p>
                </div>
              </div>

              {/* 등록된 포장 목록 */}
              <div className="space-y-2 mb-3 max-h-[40vh] overflow-y-auto">
                {packages.length === 0 ? (
                  <div className="text-center py-8 text-sm text-gray-400 border-2 border-dashed border-gray-200 rounded-xl">
                    등록된 포장이 없습니다
                  </div>
                ) : (
                  packages.map((p, idx) => (
                    <div
                      key={idx}
                      className="flex items-center gap-2 px-3 py-2.5 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-200 rounded-lg"
                    >
                      <span className="text-xl">{p.unit.icon}</span>
                      <div className="flex-1 min-w-0">
                        <p
                          className="text-sm font-bold text-gray-900"
                          style={{ fontVariantNumeric: "tabular-nums" }}
                        >
                          {p.count.toLocaleString()}
                          {p.unit.label} × {p.qtyPerUnit.toLocaleString()}EA
                        </p>
                        <p
                          className="text-xs font-bold text-green-700"
                          style={{ fontVariantNumeric: "tabular-nums" }}
                        >
                          = {(p.count * p.qtyPerUnit).toLocaleString()} EA
                        </p>
                      </div>
                      <button
                        onClick={() => openEditFlow(idx)}
                        className="w-9 h-9 rounded-lg bg-blue-100 text-blue-700 hover:bg-blue-200 flex items-center justify-center active:scale-95 transition-all"
                        title="수정"
                      >
                        <svg
                          className="w-4 h-4"
                          fill="none"
                          stroke="currentColor"
                          strokeWidth={2}
                          viewBox="0 0 24 24"
                        >
                          <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125"
                          />
                        </svg>
                      </button>
                      <button
                        onClick={() => handleDelete(idx)}
                        className="w-9 h-9 rounded-lg bg-red-100 text-red-700 hover:bg-red-200 flex items-center justify-center active:scale-95 transition-all"
                        title="삭제"
                      >
                        <svg
                          className="w-4 h-4"
                          fill="none"
                          stroke="currentColor"
                          strokeWidth={2}
                          viewBox="0 0 24 24"
                        >
                          <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0"
                          />
                        </svg>
                      </button>
                    </div>
                  ))
                )}
              </div>

              {/* 품목명 */}
              <p className="text-xs text-gray-400 truncate max-w-full px-1 mb-3 text-center">
                {itemName}
              </p>

              {/* 버튼 */}
              <div className="flex gap-2">
                <button
                  onClick={openAddFlow}
                  disabled={unpackedQty <= 0}
                  className={`flex-1 h-12 rounded-xl text-sm font-bold border-2 border-dashed transition-all ${
                    unpackedQty <= 0
                      ? "border-gray-200 text-gray-300 cursor-not-allowed"
                      : "border-blue-400 text-blue-700 hover:bg-blue-50 active:scale-95"
                  }`}
                >
                  + 포장단위 추가
                </button>
                <button
                  onClick={handleFinalConfirm}
                  disabled={packages.length === 0}
                  className={`flex-1 h-12 rounded-xl text-sm font-bold text-white transition-all ${
                    packages.length === 0
                      ? "opacity-40 cursor-not-allowed"
                      : "active:scale-95"
                  }`}
                  style={{
                    background:
                      packages.length === 0
                        ? "#9ca3af"
                        : "linear-gradient(135deg, #10b981 0%, #059669 100%)",
                  }}
                >
                  확인
                </button>
              </div>
            </>
          )}

          {/* ====== PACKAGING: 포장단위 선택 ====== */}
          {step === "packaging" && (
            <>
              <p className="text-center text-sm font-semibold text-gray-700 mb-1">
                포장 단위를 선택하세요
              </p>
              <p className="text-center text-xs text-gray-400 mb-4">
                미포장 잔량 {unpackedQty.toLocaleString()} EA
              </p>
              {renderPackagingGrid(handleSelectUnit)}
            </>
          )}

          {/* ====== COUNT: 개수 입력 ====== */}
          {step === "count" && selectedUnit && (
            <>
              <p className="text-center text-sm font-semibold text-gray-700 mb-1">
                {selectedUnit.icon} {selectedUnit.label} 몇 개?
              </p>
              <p className="text-center text-xs text-gray-400 mb-1">
                개당 {currentPkgQty.toLocaleString()}EA
              </p>
              <p className="text-center text-xs text-blue-600 mb-3">
                사용 가능 {availableForCurrent.toLocaleString()}EA · 최대{" "}
                {maxCountForCurrent.toLocaleString()}개
              </p>
              {renderNumpad(
                count,
                handleInput,
                handleCountConfirm,
                editingIndex !== null ? "수정" : "추가",
                countNum <= 0
              )}
              {countNum > 0 && (
                <div className="mt-3 text-center text-sm font-semibold px-3 py-2 rounded-lg bg-blue-50 text-blue-700 border border-blue-200">
                  {countNum}
                  {selectedUnit.label} × {currentPkgQty.toLocaleString()}EA ={" "}
                  {(countNum * currentPkgQty).toLocaleString()}EA
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
}
