"use client";

import React, { useState, useEffect, useCallback } from "react";
import { apiClient } from "@/lib/api/client";

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

export interface InspectionItem {
  id: string;
  inspection_item_name: string;
  inspection_standard: string;
  inspection_method: string;
  pass_criteria: string;
  is_required: string;
  /** User-entered measured value */
  measured_value: string;
  /** "pass" | "fail" | null */
  result: "pass" | "fail" | null;
}

export interface InspectionResult {
  items: InspectionItem[];
  goodQty: number;
  badQty: number;
  remark: string;
  completed: boolean;
}

interface InspectionModalProps {
  open: boolean;
  onClose: () => void;
  onComplete: (result: InspectionResult) => void;
  itemCode: string;
  itemName: string;
  totalQty: number;
  initialResult?: InspectionResult | null;
}

/* ------------------------------------------------------------------ */
/* Dummy inspection items (fallback)                                   */
/* ------------------------------------------------------------------ */

const DUMMY_INSPECTION_ITEMS: InspectionItem[] = [
  {
    id: "dummy-1",
    inspection_item_name: "외관 검사",
    inspection_standard: "스크래치, 변색, 찍힘 없음",
    inspection_method: "육안 검사",
    pass_criteria: "이상 없음",
    is_required: "Y",
    measured_value: "",
    result: null,
  },
  {
    id: "dummy-2",
    inspection_item_name: "치수 검사",
    inspection_standard: "규격 +-0.5mm",
    inspection_method: "캘리퍼스 측정",
    pass_criteria: "허용 오차 이내",
    is_required: "Y",
    measured_value: "",
    result: null,
  },
  {
    id: "dummy-3",
    inspection_item_name: "수량 검사",
    inspection_standard: "발주 수량과 일치",
    inspection_method: "전수 검사",
    pass_criteria: "수량 일치",
    is_required: "Y",
    measured_value: "",
    result: null,
  },
  {
    id: "dummy-4",
    inspection_item_name: "포장 상태",
    inspection_standard: "포장 손상 없음",
    inspection_method: "육안 검사",
    pass_criteria: "이상 없음",
    is_required: "",
    measured_value: "",
    result: null,
  },
];

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

export function InspectionModal({
  open,
  onClose,
  onComplete,
  itemCode,
  itemName,
  totalQty,
  initialResult,
}: InspectionModalProps) {
  const [inspItems, setInspItems] = useState<InspectionItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [goodQty, setGoodQty] = useState(0);
  const [badQty, setBadQty] = useState(0);
  const [remark, setRemark] = useState("");

  /* Fetch inspection items from DB */
  const fetchInspectionItems = useCallback(async () => {
    setLoading(true);
    try {
      const res = await apiClient.get("/pop/execute-action", {
        params: {
          taskType: "data-list",
          targetTable: "item_inspection_info",
          filters: JSON.stringify({ item_code: itemCode }),
          pageSize: "50",
        },
      });
      const data = res.data?.data;
      if (Array.isArray(data) && data.length > 0) {
        setInspItems(
          data.map((r: Record<string, unknown>) => ({
            id: String(r.id ?? ""),
            inspection_item_name: String(r.inspection_item_name ?? ""),
            inspection_standard: String(r.inspection_standard ?? ""),
            inspection_method: String(r.inspection_method ?? ""),
            pass_criteria: String(r.pass_criteria ?? ""),
            is_required: String(r.is_required ?? ""),
            measured_value: "",
            result: null,
          }))
        );
      } else {
        setInspItems(DUMMY_INSPECTION_ITEMS.map((i) => ({ ...i })));
      }
    } catch {
      setInspItems(DUMMY_INSPECTION_ITEMS.map((i) => ({ ...i })));
    } finally {
      setLoading(false);
    }
  }, [itemCode]);

  /* Init on open */
  useEffect(() => {
    if (!open) return;
    if (initialResult) {
      setInspItems(initialResult.items.map((i) => ({ ...i })));
      setGoodQty(initialResult.goodQty);
      setBadQty(initialResult.badQty);
      setRemark(initialResult.remark);
    } else {
      fetchInspectionItems();
      setGoodQty(totalQty);
      setBadQty(0);
      setRemark("");
    }
  }, [open, initialResult, fetchInspectionItems, totalQty]);

  /* Update item */
  const updateItem = (id: string, field: "measured_value" | "result", value: string) => {
    setInspItems((prev) =>
      prev.map((item) =>
        item.id === id
          ? { ...item, [field]: field === "result" ? (item.result === value ? null : value) : value }
          : item
      )
    );
  };

  /* Handle good/bad qty sync */
  const handleGoodQtyChange = (val: number) => {
    const v = Math.max(0, Math.min(val, totalQty));
    setGoodQty(v);
    setBadQty(totalQty - v);
  };

  const handleBadQtyChange = (val: number) => {
    const v = Math.max(0, Math.min(val, totalQty));
    setBadQty(v);
    setGoodQty(totalQty - v);
  };

  /* Complete */
  const handleComplete = () => {
    onComplete({
      items: inspItems,
      goodQty,
      badQty,
      remark,
      completed: true,
    });
    onClose();
  };

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex">
      {/* Full-screen slide panel */}
      <div className="absolute inset-0 bg-black/30" onClick={onClose} />
      <div
        className="relative ml-auto w-full sm:w-[420px] h-full bg-white shadow-2xl z-10 flex flex-col"
        style={{ animation: "slideInRight 0.3s ease" }}
      >
        {/* Header */}
        <div className="flex items-center justify-between px-5 py-4 border-b border-gray-200 bg-gray-50 shrink-0">
          <h3 className="text-lg font-bold text-gray-900">자주검사</h3>
          <button
            onClick={onClose}
            className="w-9 h-9 rounded-lg flex items-center justify-center text-gray-500 hover:bg-gray-200 transition-colors"
          >
            <svg className="w-5 h-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>

        {/* Scrollable body */}
        <div className="flex-1 overflow-y-auto px-5 py-4 bg-gray-50">
          {/* Item summary */}
          <div className="flex flex-wrap items-center gap-2 px-3.5 py-2.5 mb-4 rounded-lg border border-sky-200"
            style={{ background: "linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%)" }}
          >
            <span className="text-xs font-semibold text-sky-700 bg-white px-2 py-0.5 rounded shrink-0">
              {itemCode}
            </span>
            <span className="text-sm font-semibold text-gray-900 flex-1 truncate min-w-0">
              {itemName}
            </span>
            <span className="text-sm font-bold text-green-600 shrink-0">
              {totalQty.toLocaleString()} EA
            </span>
          </div>

          {/* Inspection items section */}
          <div className="bg-white rounded-xl border border-gray-200 p-3.5 mb-4">
            <div className="flex items-center justify-between mb-3">
              <h4 className="text-sm font-semibold text-gray-700">검사 항목</h4>
              <span className="text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded-full">
                {inspItems.length}개
              </span>
            </div>

            {loading ? (
              <div className="flex items-center justify-center py-8 text-sm text-gray-400">
                <svg className="animate-spin w-5 h-5 mr-2 text-blue-500" fill="none" viewBox="0 0 24 24">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
                </svg>
                불러오는 중...
              </div>
            ) : inspItems.length === 0 ? (
              <div className="text-center py-6 text-sm text-gray-400">
                등록된 검사 항목이 없습니다
              </div>
            ) : (
              <div className="flex flex-col gap-2.5 max-h-[300px] overflow-y-auto">
                {inspItems.map((item) => (
                  <div
                    key={item.id}
                    className={`bg-gray-50 border rounded-lg p-3 ${
                      item.is_required === "Y" ? "border-l-[3px] border-l-red-400 border-gray-200" : "border-gray-200"
                    }`}
                  >
                    {/* Item header */}
                    <div className="flex items-start justify-between mb-2">
                      <span className="text-[13px] font-semibold text-gray-900">
                        {item.inspection_item_name}
                      </span>
                      {item.is_required === "Y" && (
                        <span className="text-[10px] px-1.5 py-0.5 rounded bg-red-100 text-red-600 font-semibold shrink-0 ml-2">
                          필수
                        </span>
                      )}
                    </div>

                    {/* Info grid */}
                    <div className="grid grid-cols-[auto_1fr] gap-x-2.5 gap-y-1 text-xs mb-2.5">
                      {item.inspection_standard && (
                        <>
                          <span className="text-gray-400">기준</span>
                          <span className="text-gray-700">{item.inspection_standard}</span>
                        </>
                      )}
                      {item.inspection_method && (
                        <>
                          <span className="text-gray-400">방법</span>
                          <span className="text-gray-700">{item.inspection_method}</span>
                        </>
                      )}
                      {item.pass_criteria && (
                        <>
                          <span className="text-gray-400">판정</span>
                          <span className="text-gray-700">{item.pass_criteria}</span>
                        </>
                      )}
                    </div>

                    {/* Input + result buttons */}
                    <div className="flex items-center gap-2">
                      <input
                        type="text"
                        value={item.measured_value}
                        onChange={(e) => updateItem(item.id, "measured_value", e.target.value)}
                        placeholder="측정값 입력"
                        className="flex-1 h-9 px-2.5 text-[13px] border border-gray-200 rounded-md outline-none focus:border-blue-400 focus:ring-1 focus:ring-blue-100"
                      />
                      <div className="flex gap-1">
                        <button
                          onClick={() => updateItem(item.id, "result", "pass")}
                          className={`w-9 h-9 rounded-md border text-base flex items-center justify-center transition-all ${
                            item.result === "pass"
                              ? "bg-green-100 border-green-400 text-green-700"
                              : "border-gray-200 text-gray-400 hover:bg-green-50 hover:border-green-300"
                          }`}
                        >
                          {"\u2713"}
                        </button>
                        <button
                          onClick={() => updateItem(item.id, "result", "fail")}
                          className={`w-9 h-9 rounded-md border text-base flex items-center justify-center transition-all ${
                            item.result === "fail"
                              ? "bg-red-100 border-red-400 text-red-700"
                              : "border-gray-200 text-gray-400 hover:bg-red-50 hover:border-red-300"
                          }`}
                        >
                          {"\u2717"}
                        </button>
                      </div>
                      {/* Camera placeholder */}
                      <button
                        className="w-9 h-9 rounded-md border border-gray-200 text-gray-400 flex items-center justify-center hover:bg-gray-50 transition-colors"
                        title="사진 촬영 (준비 중)"
                      >
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" d="M6.827 6.175A2.31 2.31 0 015.186 7.23c-.38.054-.757.112-1.134.175C2.999 7.58 2.25 8.507 2.25 9.574V18a2.25 2.25 0 002.25 2.25h15A2.25 2.25 0 0021.75 18V9.574c0-1.067-.75-1.994-1.802-2.169a47.865 47.865 0 00-1.134-.175 2.31 2.31 0 01-1.64-1.055l-.822-1.316a2.192 2.192 0 00-1.736-1.039 48.774 48.774 0 00-5.232 0 2.192 2.192 0 00-1.736 1.039l-.821 1.316z" />
                          <path strokeLinecap="round" strokeLinejoin="round" d="M16.5 12.75a4.5 4.5 0 11-9 0 4.5 4.5 0 019 0z" />
                        </svg>
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Final judgment section */}
          <div className="bg-white rounded-xl border border-gray-200 p-3.5 mb-4">
            <h4 className="text-sm font-semibold text-gray-700 mb-3">종합 판정</h4>

            {/* Good / Bad qty */}
            <div className="grid grid-cols-2 gap-3 mb-3">
              <div className="flex flex-col gap-1">
                <label className="text-[11px] font-semibold text-green-600">양품 수량</label>
                <div className="flex items-center gap-1">
                  <input
                    type="number"
                    value={goodQty}
                    onChange={(e) => handleGoodQtyChange(parseInt(e.target.value, 10) || 0)}
                    className="flex-1 min-w-0 h-10 px-2 text-center text-sm font-semibold border-2 border-green-400 rounded-lg bg-green-50 text-green-700 outline-none focus:ring-2 focus:ring-green-200"
                  />
                  <span className="text-[11px] text-gray-500 shrink-0">EA</span>
                </div>
              </div>
              <div className="flex flex-col gap-1">
                <label className="text-[11px] font-semibold text-red-600">불량 수량</label>
                <div className="flex items-center gap-1">
                  <input
                    type="number"
                    value={badQty}
                    onChange={(e) => handleBadQtyChange(parseInt(e.target.value, 10) || 0)}
                    className="flex-1 min-w-0 h-10 px-2 text-center text-sm font-semibold border-2 border-red-400 rounded-lg bg-red-50 text-red-700 outline-none focus:ring-2 focus:ring-red-200"
                  />
                  <span className="text-[11px] text-gray-500 shrink-0">EA</span>
                </div>
              </div>
            </div>

            {/* Total summary */}
            <div className="flex items-center justify-between px-3 py-2 bg-gray-50 rounded-lg border border-gray-200">
              <span className="text-[13px] text-gray-500">전체 수량</span>
              <span className="text-[15px] font-bold text-gray-900">
                {totalQty.toLocaleString()} EA
              </span>
            </div>
          </div>

          {/* Remark */}
          <div className="bg-white rounded-xl border border-gray-200 p-3.5 mb-4">
            <h4 className="text-sm font-semibold text-gray-700 mb-2">비고</h4>
            <textarea
              value={remark}
              onChange={(e) => setRemark(e.target.value)}
              placeholder="검사 관련 특이사항 입력"
              rows={3}
              className="w-full px-3 py-2 text-sm border border-gray-200 rounded-lg outline-none focus:border-blue-400 focus:ring-1 focus:ring-blue-100 resize-none"
            />
          </div>
        </div>

        {/* Footer */}
        <div className="flex gap-2.5 px-5 py-4 border-t border-gray-200 bg-white shrink-0">
          <button
            onClick={onClose}
            className="flex-1 h-12 rounded-xl border border-gray-200 text-sm font-semibold text-gray-600 hover:bg-gray-50 active:scale-[0.98] transition-all"
          >
            취소
          </button>
          <button
            className="flex-1 h-12 rounded-xl border border-gray-200 text-sm font-semibold text-gray-500 hover:bg-gray-50 active:scale-[0.98] transition-all"
            title="준비 중"
          >
            성적서 출력
          </button>
          <button
            onClick={handleComplete}
            className="flex-[2] h-12 rounded-xl text-sm font-bold text-white active:scale-[0.98] transition-all"
            style={{
              background: "linear-gradient(to bottom, #60a5fa, #2563eb)",
              boxShadow: "0 4px 12px rgba(59,130,246,.3)",
            }}
          >
            검사 완료
          </button>
        </div>
      </div>

      {/* Global keyframe (only mounts once) */}
      <style dangerouslySetInnerHTML={{ __html: `
        @keyframes slideInRight {
          from { transform: translateX(100%); }
          to { transform: translateX(0); }
        }
      ` }} />
    </div>
  );
}
