"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Trash2, Plus } from "lucide-react";
import Swal from "sweetalert2";

interface Vendor { OBJID: string; VENDOR_NAME: string }
interface Wh { OBJID: string; WH_NAME: string }
interface Item { OBJID: string; ITEM_CODE: string; ITEM_NAME: string; COST_PRICE: number }
interface Proc { OBJID: string; PROC_NO: string; VENDOR_OBJID: string; VENDOR_NAME: string }
interface ProcLine { OBJID: string; ITEM_OBJID: string; ITEM_NAME: string; QTY: number; COST_PRICE: number; RECEIVED_QTY: number }
interface Line { itemObjid: string; itemName: string; qtyNormal: number; qtyDefect: number; costPrice: number; defectReason?: string }
const fmt = (n: number) => Number(n || 0).toLocaleString("ko-KR");

export default function NewInboundPage() {
  const router = useRouter();
  const [vendors, setVendors] = useState<Vendor[]>([]);
  const [whs, setWhs] = useState<Wh[]>([]);
  const [items, setItems] = useState<Item[]>([]);
  const [procs, setProcs] = useState<Proc[]>([]);

  const [procObjid, setProcObjid] = useState("");
  const [vendorObjid, setVendorObjid] = useState("");
  const [whObjid, setWhObjid] = useState("");
  const [inboundDate, setInboundDate] = useState(new Date().toISOString().slice(0, 10));
  const [lines, setLines] = useState<Line[]>([]);
  const [memo, setMemo] = useState("");

  // 단일 입고 라인 입력용
  const [pickItem, setPickItem] = useState("");
  const [qtyN, setQtyN] = useState(0);
  const [qtyD, setQtyD] = useState(0);
  const [defectReason, setDefectReason] = useState("");
  const [costPrice, setCostPrice] = useState(0);

  useEffect(() => {
    fetch("/api/m/vendors/list", { method: "POST" }).then((r) => r.json()).then((j) => setVendors(j.RESULTLIST || []));
    fetch("/api/m/warehouses/list", { method: "POST" }).then((r) => r.json()).then((j) => setWhs(j.RESULTLIST || []));
    fetch("/api/m/items/list", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" }).then((r) => r.json()).then((j) => setItems(j.RESULTLIST || []));
    fetch("/api/m/procurements/list", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ status: "OPEN" }) }).then((r) => r.json()).then((j) => setProcs(j.RESULTLIST || []));
  }, []);

  // 매입발주 선택 시 라인 자동 로드
  const onProcChange = async (id: string) => {
    setProcObjid(id);
    if (!id) return;
    const res = await fetch("/api/m/procurements/detail", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ objid: id }),
    });
    const j = await res.json();
    if (j.success) {
      setVendorObjid(j.proc.VENDOR_OBJID || "");
      setLines((j.items as ProcLine[]).map((it) => ({
        itemObjid: it.ITEM_OBJID,
        itemName: it.ITEM_NAME,
        qtyNormal: Math.max(0, Number(it.QTY) - Number(it.RECEIVED_QTY)),
        qtyDefect: 0,
        costPrice: Number(it.COST_PRICE),
      })));
    }
  };

  const addManual = () => {
    if (!pickItem) return;
    const it = items.find((x) => x.OBJID === pickItem);
    if (!it) return;
    setLines([...lines, {
      itemObjid: it.OBJID, itemName: it.ITEM_NAME,
      qtyNormal: qtyN, qtyDefect: qtyD,
      costPrice: costPrice || Number(it.COST_PRICE) || 0,
      defectReason: qtyD > 0 ? defectReason : undefined,
    }]);
    setPickItem(""); setQtyN(0); setQtyD(0); setDefectReason(""); setCostPrice(0);
  };

  const update = (i: number, k: keyof Line, v: number | string) => {
    setLines(lines.map((ln, j) => j === i ? { ...ln, [k]: v } : ln));
  };

  const submit = async () => {
    if (!whObjid) return Swal.fire({ icon: "warning", title: "창고 선택" });
    if (lines.length === 0) return Swal.fire({ icon: "warning", title: "라인 추가" });
    const res = await fetch("/api/m/inbounds/save", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ procObjid: procObjid || undefined, vendorObjid, whObjid, inboundDate, lines, memo }),
    });
    const j = await res.json();
    if (j.success) {
      await Swal.fire({ icon: "success", title: "입고 완료", text: `입고번호: ${j.inboundNo}` });
      router.push("/m/admin/inbounds");
    } else Swal.fire({ icon: "error", title: "오류", text: j.message });
  };

  const total = lines.reduce((a, l) => a + Math.round(l.costPrice * (l.qtyNormal + l.qtyDefect)), 0);

  return (
    <div className="space-y-4 max-w-4xl">
      <h1 className="text-2xl font-bold">입고 처리</h1>
      <div className="bg-white border rounded-xl p-5 space-y-3">
        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className="text-xs font-semibold text-slate-600">매입발주 (선택 시 라인 자동입력)</label>
            <select value={procObjid} onChange={(e) => onProcChange(e.target.value)} className="w-full h-10 px-3 rounded-lg border border-slate-200 mt-1">
              <option value="">단독 입고 (매입발주 없이)</option>
              {procs.map((p) => <option key={p.OBJID} value={p.OBJID}>{p.PROC_NO} — {p.VENDOR_NAME}</option>)}
            </select>
          </div>
          <div>
            <label className="text-xs font-semibold text-slate-600">공급업체</label>
            <select value={vendorObjid} onChange={(e) => setVendorObjid(e.target.value)} className="w-full h-10 px-3 rounded-lg border border-slate-200 mt-1">
              <option value="">선택</option>
              {vendors.map((v) => <option key={v.OBJID} value={v.OBJID}>{v.VENDOR_NAME}</option>)}
            </select>
          </div>
          <div>
            <label className="text-xs font-semibold text-slate-600">입고 창고 *</label>
            <select value={whObjid} onChange={(e) => setWhObjid(e.target.value)} className="w-full h-10 px-3 rounded-lg border border-slate-200 mt-1">
              <option value="">선택</option>
              {whs.map((w) => <option key={w.OBJID} value={w.OBJID}>{w.WH_NAME}</option>)}
            </select>
          </div>
          <div>
            <label className="text-xs font-semibold text-slate-600">입고일</label>
            <input type="date" value={inboundDate} onChange={(e) => setInboundDate(e.target.value)} className="w-full h-10 px-3 rounded-lg border border-slate-200 mt-1" />
          </div>
        </div>
      </div>

      <div className="bg-white border rounded-xl p-5">
        <h3 className="font-bold mb-3">입고 라인 (정상 + 불량 분리)</h3>
        <div className="grid grid-cols-12 gap-2 mb-3">
          <select value={pickItem} onChange={(e) => setPickItem(e.target.value)} className="col-span-4 h-10 px-3 rounded-lg border border-slate-200">
            <option value="">품목 선택</option>
            {items.map((i) => <option key={i.OBJID} value={i.OBJID}>{i.ITEM_NAME}</option>)}
          </select>
          <input type="number" min={0} value={qtyN} onChange={(e) => setQtyN(Number(e.target.value))} placeholder="정상" className="col-span-1 h-10 px-2 rounded-lg border border-slate-200 text-right" />
          <input type="number" min={0} value={qtyD} onChange={(e) => setQtyD(Number(e.target.value))} placeholder="불량" className="col-span-1 h-10 px-2 rounded-lg border border-slate-200 text-right" />
          <input type="text" value={defectReason} onChange={(e) => setDefectReason(e.target.value)} placeholder="불량사유" className="col-span-3 h-10 px-3 rounded-lg border border-slate-200" />
          <input type="number" min={0} value={costPrice} onChange={(e) => setCostPrice(Number(e.target.value))} placeholder="단가" className="col-span-2 h-10 px-2 rounded-lg border border-slate-200 text-right" />
          <button onClick={addManual} className="col-span-1 h-10 rounded-lg bg-slate-800 text-white text-sm font-bold flex items-center justify-center"><Plus size={14} /></button>
        </div>

        <table className="w-full text-sm border">
          <thead className="bg-slate-50 text-xs">
            <tr>
              <th className="px-3 py-2 text-left">품목</th>
              <th className="px-2 py-2 text-right text-emerald-700">정상</th>
              <th className="px-2 py-2 text-right text-rose-600">불량</th>
              <th className="px-2 py-2 text-left">불량사유</th>
              <th className="px-2 py-2 text-right">단가</th>
              <th className="px-2 py-2 text-right">합계</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {lines.length === 0 ? (
              <tr><td colSpan={7} className="text-center py-6 text-slate-400">매입발주 선택 또는 라인 추가</td></tr>
            ) : lines.map((ln, i) => (
              <tr key={i} className="border-t">
                <td className="px-3 py-1.5 text-sm">{ln.itemName}</td>
                <td className="px-1"><input type="number" min={0} value={ln.qtyNormal} onChange={(e) => update(i, "qtyNormal", Number(e.target.value))} className="w-20 h-8 px-2 text-right border border-emerald-200 rounded text-emerald-700 font-semibold" /></td>
                <td className="px-1"><input type="number" min={0} value={ln.qtyDefect} onChange={(e) => update(i, "qtyDefect", Number(e.target.value))} className="w-20 h-8 px-2 text-right border border-rose-200 rounded text-rose-700 font-semibold" /></td>
                <td className="px-1"><input type="text" value={ln.defectReason ?? ""} onChange={(e) => update(i, "defectReason", e.target.value)} className="w-full h-8 px-2 border border-slate-200 rounded text-xs" placeholder="-" /></td>
                <td className="px-1"><input type="number" min={0} value={ln.costPrice} onChange={(e) => update(i, "costPrice", Number(e.target.value))} className="w-24 h-8 px-2 text-right border border-slate-200 rounded" /></td>
                <td className="px-2 py-1.5 text-right tabular-nums font-bold">₩{fmt(Math.round(ln.costPrice * (ln.qtyNormal + ln.qtyDefect)))}</td>
                <td className="px-2 py-1.5 text-right"><button onClick={() => setLines(lines.filter((_, j) => j !== i))} className="text-slate-400 hover:text-rose-500"><Trash2 size={14} /></button></td>
              </tr>
            ))}
          </tbody>
          {lines.length > 0 && (
            <tfoot className="bg-slate-50">
              <tr><td colSpan={5} className="px-3 py-2 text-right font-bold">합계</td><td className="px-2 py-2 text-right font-bold tabular-nums text-emerald-700">₩{fmt(total)}</td><td></td></tr>
            </tfoot>
          )}
        </table>
        <textarea placeholder="메모 (선택)" value={memo} onChange={(e) => setMemo(e.target.value)} rows={2} className="w-full mt-4 px-3 py-2 rounded-lg border border-slate-200 text-sm" />

        <div className="bg-amber-50 border border-amber-200 rounded p-3 text-xs text-amber-800 mt-3">
          ⓘ 정상 수량만 재고에 +됩니다. 불량 수량은 별도 기록되어 재고 미반영.
        </div>
      </div>

      <div className="flex justify-end gap-2">
        <button onClick={() => router.back()} className="px-5 h-11 rounded-xl border border-slate-200 font-semibold">취소</button>
        <button onClick={submit} className="px-6 h-11 rounded-xl bg-emerald-700 text-white font-bold">입고 처리</button>
      </div>
    </div>
  );
}
