"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 Item { OBJID: string; ITEM_CODE: string; ITEM_NAME: string; COST_PRICE: number }
interface Line { itemObjid: string; itemName: string; qty: number; costPrice: number }
const fmt = (n: number) => Number(n || 0).toLocaleString("ko-KR");

export default function NewProcPage() {
  const router = useRouter();
  const [vendors, setVendors] = useState<Vendor[]>([]);
  const [items, setItems] = useState<Item[]>([]);
  const [vendorObjid, setVendorObjid] = useState("");
  const [procDate, setProcDate] = useState(new Date().toISOString().slice(0, 10));
  const [lines, setLines] = useState<Line[]>([]);
  const [pickItem, setPickItem] = useState("");
  const [pickQty, setPickQty] = useState(10);
  const [pickPrice, setPickPrice] = useState(0);
  const [memo, setMemo] = useState("");

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

  const addLine = () => {
    if (!pickItem) return;
    const it = items.find((x) => x.OBJID === pickItem);
    if (!it) return;
    setLines([...lines, { itemObjid: it.OBJID, itemName: it.ITEM_NAME, qty: pickQty, costPrice: pickPrice || Number(it.COST_PRICE) || 0 }]);
    setPickItem(""); setPickQty(10); setPickPrice(0);
  };

  const submit = async () => {
    if (!vendorObjid) return Swal.fire({ icon: "warning", title: "공급업체 선택" });
    if (lines.length === 0) return Swal.fire({ icon: "warning", title: "발주 라인 추가" });
    const res = await fetch("/api/m/procurements/save", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ vendorObjid, procDate, lines, memo }),
    });
    const j = await res.json();
    if (j.success) {
      await Swal.fire({ icon: "success", title: "발주 등록", text: `발주번호: ${j.procNo}` });
      router.push("/m/admin/procurements");
    } else Swal.fire({ icon: "error", title: "오류", text: j.message });
  };

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

  return (
    <div className="space-y-4 max-w-3xl">
      <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={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>
            <input type="date" value={procDate} onChange={(e) => setProcDate(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="flex gap-2 mb-3">
          <select value={pickItem} onChange={(e) => setPickItem(e.target.value)} className="flex-1 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={1} value={pickQty} onChange={(e) => setPickQty(Number(e.target.value))} placeholder="수량" className="w-24 h-10 px-3 rounded-lg border border-slate-200" />
          <input type="number" min={0} value={pickPrice} onChange={(e) => setPickPrice(Number(e.target.value))} placeholder="단가" className="w-32 h-10 px-3 rounded-lg border border-slate-200" />
          <button onClick={addLine} className="h-10 px-4 rounded-lg bg-slate-800 text-white text-sm font-bold flex items-center gap-1"><Plus size={14} />추가</button>
        </div>
        <table className="w-full text-sm border">
          <thead className="bg-slate-50">
            <tr><th className="px-3 py-2 text-left text-xs">품목</th><th className="px-3 py-2 text-right text-xs">수량</th><th className="px-3 py-2 text-right text-xs">단가</th><th className="px-3 py-2 text-right text-xs">합계</th><th></th></tr>
          </thead>
          <tbody>
            {lines.length === 0 ? (
              <tr><td colSpan={5} 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-2">{ln.itemName}</td>
                <td className="px-3 py-2 text-right">{ln.qty}</td>
                <td className="px-3 py-2 text-right tabular-nums">₩{fmt(ln.costPrice)}</td>
                <td className="px-3 py-2 text-right tabular-nums font-bold">₩{fmt(Math.round(ln.qty * ln.costPrice))}</td>
                <td className="px-3 py-2 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={3} className="px-3 py-2 text-right font-bold">합계</td><td className="px-3 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>

      <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>
  );
}
