"use client";

import { useState, useEffect, useCallback } from "react";
import { useSearchParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import Swal from "sweetalert2";

interface PartRow {
  PART_OBJID: string; PART_NO: string; PART_NAME: string;
  ORDER_QTY: string; ARRIVAL_OBJID?: string;
  ARRIVAL_QTY: string; ARRIVAL_PLAN_DATE: string;
}

export default function ArrivalPlanPage() {
  const searchParams = useSearchParams();
  const objId = searchParams.get("objId") || "";
  const [parts, setParts] = useState<PartRow[]>([]);
  const [loading, setLoading] = useState(false);

  const fetchData = useCallback(async () => {
    if (!objId) return;
    const res = await fetch("/api/delivery/acceptance/detail", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ objId }),
    });
    const json = await res.json();
    if (json.success) {
      setParts((json.PARTS || []).map((p: Record<string, unknown>) => ({
        PART_OBJID: String(p.PART_OBJID || ""),
        PART_NO: String(p.PART_NO || ""), PART_NAME: String(p.PART_NAME || ""),
        ORDER_QTY: String(p.ORDER_QTY || "0"),
        ARRIVAL_OBJID: String(p.ARRIVAL_OBJID || ""),
        ARRIVAL_QTY: String(p.ARRIVAL_QTY || p.ORDER_QTY || "0"),
        ARRIVAL_PLAN_DATE: String(p.ARRIVAL_PLAN_DATE || ""),
      })));
    }
  }, [objId]);

  useEffect(() => { fetchData(); }, [fetchData]);

  const updatePart = (i: number, k: keyof PartRow, v: string) =>
    setParts((prev) => { const n = [...prev]; n[i] = { ...n[i], [k]: v }; return n; });

  const handleSave = async () => {
    setLoading(true);
    try {
      const items = parts.map((p) => ({
        objId: p.ARRIVAL_OBJID || undefined,
        parent_objid: objId, order_part_objid: p.PART_OBJID, part_objid: p.PART_OBJID,
        arrival_qty: p.ARRIVAL_QTY, arrival_plan_date: p.ARRIVAL_PLAN_DATE,
        receipt_qty: "0",
      }));
      const res = await fetch("/api/delivery/acceptance/save", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ items }),
      });
      const json = await res.json();
      if (json.success) {
        Swal.fire({ icon: "success", title: "입고계획이 등록되었습니다.", timer: 1500, showConfirmButton: false });
        if (window.opener) { try { window.opener.location.reload(); } catch {} }
      } else Swal.fire("오류", json.message, "error");
    } finally { setLoading(false); }
  };

  return (
    <div className="p-5">
      <h2 className="text-lg font-bold text-gray-800 mb-4">입고계획 등록</h2>
      <div className="border rounded overflow-auto" style={{ maxHeight: "calc(100vh - 200px)" }}>
        <table className="w-full text-xs">
          <thead className="bg-gray-50 sticky top-0">
            <tr>
              <th className="p-2 text-left">PART NO</th>
              <th className="p-2 text-left">PART NAME</th>
              <th className="p-2 w-[70px]">발주수량</th>
              <th className="p-2 w-[80px]">계획수량</th>
              <th className="p-2 w-[110px]">입고계획일</th>
            </tr>
          </thead>
          <tbody>
            {parts.map((p, i) => (
              <tr key={i} className="border-t">
                <td className="p-1.5">{p.PART_NO}</td>
                <td className="p-1.5">{p.PART_NAME}</td>
                <td className="p-1.5 text-right">{p.ORDER_QTY}</td>
                <td className="p-1"><Input type="number" value={p.ARRIVAL_QTY} onChange={(e) => updatePart(i, "ARRIVAL_QTY", e.target.value)} className="h-7 text-xs text-right" /></td>
                <td className="p-1"><Input type="date" value={p.ARRIVAL_PLAN_DATE} onChange={(e) => updatePart(i, "ARRIVAL_PLAN_DATE", e.target.value)} className="h-7 text-xs" /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="flex justify-center gap-3 mt-4">
        <Button onClick={handleSave} disabled={loading}>{loading ? "저장 중..." : "저장"}</Button>
        <Button variant="secondary" onClick={() => window.close()}>닫기</Button>
      </div>
    </div>
  );
}
