"use client";

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

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

export interface DefectType {
  id: string;
  defect_code: string;
  defect_name: string;
  defect_type: string;
  severity: string;
}

export interface DefectEntry {
  defect_code: string;
  defect_name: string;
  qty: string;
  disposition: "scrap" | "rework" | "accept";
}

interface DefectTypeModalProps {
  open: boolean;
  onClose: () => void;
  onConfirm: (entries: DefectEntry[]) => void;
  defectTypes: DefectType[];
  maxQty: number;
  initialEntries?: DefectEntry[];
}

/* ------------------------------------------------------------------ */
/* Simple Number Input with Stepper                                    */
/* ------------------------------------------------------------------ */

function QtyInput({
  value,
  onChange,
  max,
}: {
  value: number;
  onChange: (v: number) => void;
  max: number;
}) {
  const [padOpen, setPadOpen] = useState(false);
  const [padValue, setPadValue] = useState(String(value));

  const handlePadOpen = () => {
    setPadValue("");
    setPadOpen(true);
  };

  const handlePadKey = (key: string) => {
    if (key === "backspace") {
      setPadValue((prev) => prev.length > 1 ? prev.slice(0, -1) : "0");
    } else if (key === "clear") {
      setPadValue("0");
    } else if (key === "max") {
      setPadValue(String(max));
    } else {
      setPadValue((prev) => prev === "0" ? key : prev + key);
    }
  };

  const handlePadConfirm = () => {
    const num = Math.min(Math.max(0, parseInt(padValue, 10) || 0), max);
    onChange(num);
    setPadOpen(false);
  };

  return (
    <>
      <div className="flex items-center gap-2">
        <button
          onClick={() => onChange(Math.max(0, value - 1))}
          className="w-10 h-10 rounded-lg bg-gray-100 text-gray-600 text-lg font-bold flex items-center justify-center active:scale-95 transition-all hover:bg-gray-200"
        >
          -
        </button>
        <button
          onClick={handlePadOpen}
          className="w-16 h-10 text-center text-lg font-bold text-gray-900 bg-gray-50 rounded-lg border-2 border-gray-200 hover:border-red-300 active:scale-95 transition-all"
          style={{ fontVariantNumeric: "tabular-nums" }}
        >
          {value}
        </button>
        <button
          onClick={() => onChange(Math.min(max, value + 1))}
          className="w-10 h-10 rounded-lg bg-gray-100 text-gray-600 text-lg font-bold flex items-center justify-center active:scale-95 transition-all hover:bg-gray-200"
        >
          +
        </button>
      </div>

      {/* 숫자 키패드 모달 */}
      {padOpen && (
        <div className="fixed inset-0 z-[60] flex items-center justify-center">
          <div className="absolute inset-0 bg-black/40" onClick={() => setPadOpen(false)} />
          <div className="relative bg-white rounded-2xl shadow-2xl p-4 w-[280px] z-10">
            <div className="text-center mb-3">
              <p className="text-sm text-gray-500">불량 수량 (최대 {max})</p>
              <p className="text-3xl font-bold text-gray-900 mt-1" style={{ fontVariantNumeric: "tabular-nums" }}>{padValue || "0"}</p>
            </div>
            <div className="grid grid-cols-3 gap-2 mb-3">
              {["1","2","3","4","5","6","7","8","9"].map((k) => (
                <button key={k} onClick={() => handlePadKey(k)}
                  className="h-12 rounded-xl bg-gray-100 text-lg font-bold text-gray-800 active:scale-95 active:bg-gray-200 transition-all">{k}</button>
              ))}
              <button onClick={() => handlePadKey("clear")}
                className="h-12 rounded-xl bg-gray-200 text-sm font-bold text-gray-600 active:scale-95 transition-all">C</button>
              <button onClick={() => handlePadKey("0")}
                className="h-12 rounded-xl bg-gray-100 text-lg font-bold text-gray-800 active:scale-95 transition-all">0</button>
              <button onClick={() => handlePadKey("backspace")}
                className="h-12 rounded-xl bg-gray-200 text-sm font-bold text-gray-600 active:scale-95 transition-all">←</button>
            </div>
            <button onClick={() => handlePadKey("max")}
              className="w-full h-10 rounded-xl bg-red-50 text-red-600 text-sm font-bold mb-2 active:scale-95 transition-all">MAX ({max})</button>
            <div className="flex gap-2">
              <button onClick={() => setPadOpen(false)}
                className="flex-1 h-11 rounded-xl bg-gray-100 text-gray-700 font-semibold active:scale-95 transition-all">취소</button>
              <button onClick={handlePadConfirm}
                className="flex-1 h-11 rounded-xl bg-red-500 text-white font-bold active:scale-95 transition-all">확인</button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

/* ------------------------------------------------------------------ */
/* Disposition labels                                                   */
/* ------------------------------------------------------------------ */

const DISPOSITIONS: { value: DefectEntry["disposition"]; label: string; color: string }[] = [
  { value: "scrap", label: "폐기", color: "bg-red-100 text-red-700 border-red-200" },
  { value: "rework", label: "재작업", color: "bg-amber-100 text-amber-700 border-amber-200" },
  { value: "accept", label: "특채", color: "bg-blue-100 text-blue-700 border-blue-200" },
];

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

export function DefectTypeModal({
  open,
  onClose,
  onConfirm,
  defectTypes,
  maxQty,
  initialEntries,
}: DefectTypeModalProps) {
  const [entries, setEntries] = useState<
    Array<{ defect_code: string; defect_name: string; qty: number; disposition: DefectEntry["disposition"] }>
  >([]);

  useEffect(() => {
    if (open) {
      if (initialEntries && initialEntries.length > 0) {
        setEntries(
          initialEntries.map((e) => ({
            ...e,
            qty: parseInt(e.qty, 10) || 0,
          }))
        );
      } else {
        setEntries([]);
      }
    }
  }, [open, initialEntries]);

  const totalDefectQty = entries.reduce((sum, e) => sum + e.qty, 0);

  const addEntry = (dt: DefectType) => {
    // If already exists, just increment
    const existing = entries.find((e) => e.defect_code === dt.defect_code);
    if (existing) {
      setEntries((prev) =>
        prev.map((e) =>
          e.defect_code === dt.defect_code ? { ...e, qty: Math.min(e.qty + 1, maxQty) } : e
        )
      );
    } else {
      setEntries((prev) => [
        ...prev,
        {
          defect_code: dt.defect_code,
          defect_name: dt.defect_name,
          qty: 1,
          disposition: "scrap" as const,
        },
      ]);
    }
  };

  const removeEntry = (code: string) => {
    setEntries((prev) => prev.filter((e) => e.defect_code !== code));
  };

  const updateQty = (code: string, qty: number) => {
    setEntries((prev) =>
      prev.map((e) => (e.defect_code === code ? { ...e, qty } : e))
    );
  };

  const updateDisposition = (code: string, disposition: DefectEntry["disposition"]) => {
    setEntries((prev) =>
      prev.map((e) => (e.defect_code === code ? { ...e, disposition } : e))
    );
  };

  const handleConfirm = () => {
    const validEntries = entries.filter((e) => e.qty > 0);
    onConfirm(
      validEntries.map((e) => ({
        defect_code: e.defect_code,
        defect_name: e.defect_name,
        qty: String(e.qty),
        disposition: e.disposition,
      }))
    );
    onClose();
  };

  if (!open) return null;

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

      {/* Panel */}
      <div className="relative bg-white w-full sm:w-[90%] sm:max-w-[480px] rounded-t-2xl sm:rounded-2xl shadow-2xl z-10 overflow-hidden max-h-[85dvh] flex flex-col">
        {/* Header */}
        <div
          className="flex items-center justify-between px-4 py-3 shrink-0"
          style={{ background: "linear-gradient(135deg, #ef4444 0%, #b91c1c 100%)" }}
        >
          <span className="text-white font-bold text-base">불량 유형 선택</span>
          <div className="flex items-center gap-3">
            <span className="text-white/80 text-xs bg-white/20 px-2.5 py-1 rounded-full">
              총 {totalDefectQty}개
            </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>
        </div>

        {/* Body */}
        <div className="flex-1 overflow-y-auto p-4">
          {/* Defect type selection */}
          <p className="text-sm font-semibold text-gray-700 mb-3">불량 유형 선택</p>
          <div className="grid grid-cols-2 gap-2 mb-4">
            {defectTypes.map((dt) => {
              const isSelected = entries.some((e) => e.defect_code === dt.defect_code);
              return (
                <button
                  key={dt.id}
                  onClick={() => addEntry(dt)}
                  className={`px-3 py-3 rounded-xl text-sm font-medium border-2 active:scale-95 transition-all text-left ${
                    isSelected
                      ? "border-red-400 bg-red-50 text-red-700"
                      : "border-gray-200 bg-white text-gray-700 hover:border-red-300 hover:bg-red-50"
                  }`}
                >
                  <span className="block font-bold">{dt.defect_name}</span>
                  <span className="block text-xs text-gray-400 mt-0.5">{dt.defect_code}</span>
                </button>
              );
            })}
            {defectTypes.length === 0 && (
              <div className="col-span-2 text-center py-6 text-gray-400 text-sm">
                등록된 불량 유형이 없습니다
              </div>
            )}
          </div>

          {/* Selected entries */}
          {entries.length > 0 && (
            <>
              <p className="text-sm font-semibold text-gray-700 mb-3">불량 상세</p>
              <div className="flex flex-col gap-3">
                {entries.map((entry) => (
                  <div
                    key={entry.defect_code}
                    className="border-2 border-red-100 rounded-xl p-3 bg-red-50/50"
                  >
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-sm font-bold text-gray-900">{entry.defect_name}</span>
                      <button
                        onClick={() => removeEntry(entry.defect_code)}
                        className="w-7 h-7 rounded-lg bg-red-100 text-red-500 flex items-center justify-center hover:bg-red-200 active:scale-95 transition-all"
                      >
                        <svg className="w-3.5 h-3.5" 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>

                    {/* Qty */}
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-xs text-gray-500">수량</span>
                      <QtyInput
                        value={entry.qty}
                        onChange={(v) => updateQty(entry.defect_code, v)}
                        max={maxQty}
                      />
                    </div>

                    {/* Disposition */}
                    <div className="flex gap-2">
                      {DISPOSITIONS.map((d) => (
                        <button
                          key={d.value}
                          onClick={() => updateDisposition(entry.defect_code, d.value)}
                          className={`flex-1 py-2 rounded-lg text-xs font-semibold border active:scale-95 transition-all ${
                            entry.disposition === d.value
                              ? d.color
                              : "bg-white text-gray-400 border-gray-200"
                          }`}
                        >
                          {d.label}
                        </button>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            </>
          )}
        </div>

        {/* Footer */}
        <div className="shrink-0 border-t border-gray-200 p-4 flex gap-3">
          <button
            onClick={onClose}
            className="flex-1 h-12 rounded-xl text-base font-semibold bg-gray-100 text-gray-700 hover:bg-gray-200 active:scale-95 transition-all"
          >
            취소
          </button>
          <button
            onClick={handleConfirm}
            disabled={entries.length === 0 || totalDefectQty <= 0}
            className="flex-1 h-12 rounded-xl text-base font-bold text-white active:scale-95 transition-all disabled:opacity-40"
            style={{
              background:
                entries.length === 0 || totalDefectQty <= 0
                  ? "#9ca3af"
                  : "linear-gradient(135deg, #ef4444 0%, #b91c1c 100%)",
            }}
          >
            확인 ({totalDefectQty}개)
          </button>
        </div>
      </div>
    </div>
  );
}
