"use client";

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

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

export interface PackageUnit {
  label: string;
  icon: string;
  value: string;
  pkg_qty?: number;
}

interface PackagingModalProps {
  open: boolean;
  onClose: () => void;
  onSelect: (unit: PackageUnit) => void;
  itemNumber?: string;
}

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

export function PackagingModal({ open, onClose, onSelect, itemNumber }: PackagingModalProps) {
  const [units, setUnits] = useState<PackageUnit[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!open || !itemNumber) {
      setUnits([]);
      return;
    }

    let cancelled = false;
    setLoading(true);

    getPkgUnitsByItem(itemNumber)
      .then((res) => {
        if (cancelled) return;
        const mapped: PackageUnit[] = res.data.map((pu: PkgUnitByItem) => ({
          label: pu.pkg_name,
          icon: "\uD83D\uDCE6",
          value: pu.pkg_code,
          pkg_qty: pu.pkg_qty,
        }));
        setUnits(mapped);
      })
      .catch(() => {
        if (!cancelled) setUnits([]);
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });

    return () => { cancelled = true; };
  }, [open, itemNumber]);

  if (!open) return null;

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

      {/* Panel */}
      <div className="relative bg-white w-[90%] max-w-[360px] rounded-2xl shadow-2xl z-10 overflow-hidden">
        {/* Header */}
        <div className="flex items-center justify-between px-5 py-4 border-b border-gray-100">
          <h3 className="text-lg font-bold text-gray-900">
            <span className="mr-1.5">{"\uD83D\uDCE6"}</span>
            포장 단위 선택
          </h3>
          <button
            onClick={onClose}
            className="w-8 h-8 rounded-lg bg-gray-100 flex items-center justify-center text-gray-500 hover:bg-gray-200 transition-colors"
          >
            <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-5">
          {loading ? (
            <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>
          ) : units.length === 0 ? (
            <div className="text-center py-8 text-sm text-gray-400">
              등록된 포장단위가 없습니다
            </div>
          ) : (
            <div className="grid grid-cols-3 gap-3">
              {units.map((unit) => (
                <button
                  key={unit.value}
                  onClick={() => {
                    onSelect(unit);
                    onClose();
                  }}
                  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>
          )}
        </div>
      </div>
    </div>
  );
}
