"use client";

import { useState, useCallback, useEffect } from "react";
import { DataGrid, type GridColumn } from "@/components/grid/data-grid";
import { SearchForm, SearchField } from "@/components/layout/search-form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import Swal from "sweetalert2";

// purchaseOrder/purchaseOrderList.jsp 대응 - 발주관리
export default function PurchaseOrderPage() {
  const [year, setYear] = useState(new Date().getFullYear().toString());
  const [poNo, setPoNo] = useState("");
  const [supplierName, setSupplierName] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);
  const [selectedRows, setSelectedRows] = useState<Record<string, unknown>[]>([]);

  const columns: GridColumn[] = [
    { title: "발주번호", field: "PO_NO", width: 140, hozAlign: "left",
      cellClick: (row) => {
        const w = 1150, h = 850;
        const left = (window.screen.width - w) / 2, top = (window.screen.height - h) / 2;
        window.open(`/purchase-order/form?objId=${row.OBJID}`, "poForm", `width=${w},height=${h},left=${left},top=${top}`);
      } },
    { title: "프로젝트번호", field: "PROJECT_NO", width: 120, hozAlign: "center" },
    { title: "협력사", field: "SUPPLIER_NAME", width: 150, hozAlign: "left" },
    { title: "발주명", field: "PO_NAME", width: 200, hozAlign: "left" },
    { title: "발주일", field: "PO_DATE", width: 100, hozAlign: "center" },
    { title: "납기일", field: "DELIVERY_DATE", width: 100, hozAlign: "center" },
    { title: "발주금액", field: "PO_AMOUNT", width: 120, hozAlign: "right", formatter: "money" },
    { title: "상태", field: "STATUS_NAME", width: 80, hozAlign: "center" },
    { title: "등록자", field: "WRITER_NAME", width: 90, hozAlign: "center" },
  ];

  const fetchData = useCallback(async () => {
    const res = await fetch("/api/purchase-order", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ year, po_no: poNo, supplier_name: supplierName }),
    });
    if (res.ok) {
      const json = await res.json();
      setData(json.RESULTLIST || []);
    }
  }, [year, poNo, supplierName]);

  // 페이지 진입 시 자동 로드
  useEffect(() => { fetchData(); }, [fetchData]);

  return (
    <div>
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-bold text-gray-800">발주관리</h2>
        <div className="flex gap-2">
          <Button size="sm" onClick={() => {
            const w = 1150, h = 850;
            const left = (window.screen.width - w) / 2, top = (window.screen.height - h) / 2;
            window.open("/purchase-order/form", "poForm", `width=${w},height=${h},left=${left},top=${top}`);
          }}>등록</Button>
          <Button size="sm" variant="danger" onClick={async () => {
            if (selectedRows.length === 0) { Swal.fire("알림", "삭제할 항목을 선택하세요.", "warning"); return; }
            const r = await Swal.fire({ title: "삭제 확인", text: `선택한 ${selectedRows.length}건을 삭제하시겠습니까?`, icon: "warning", showCancelButton: true, confirmButtonText: "삭제", cancelButtonText: "취소" });
            if (!r.isConfirmed) return;
            const res = await fetch("/api/purchase-order/delete", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ objIds: selectedRows.map((r) => String(r.OBJID)) }) });
            const json = await res.json();
            if (json.success) { Swal.fire({ icon: "success", title: json.message, timer: 1200, showConfirmButton: false }); fetchData(); }
            else Swal.fire("오류", json.message, "error");
          }}>삭제</Button>
          <Button size="sm" variant="secondary" onClick={fetchData}>조회</Button>
        </div>
      </div>

      <SearchForm onSearch={fetchData}>
        <SearchField label="년도">
          <select value={year} onChange={(e) => setYear(e.target.value)}
            className="h-9 w-[100px] rounded border border-gray-300 bg-white px-3 text-sm">
            {Array.from({ length: 5 }, (_, i) => new Date().getFullYear() - i).map((y) => (
              <option key={y} value={y}>{y}</option>
            ))}
          </select>
        </SearchField>
        <SearchField label="발주번호">
          <Input value={poNo} onChange={(e) => setPoNo(e.target.value)} className="w-[140px]" />
        </SearchField>
        <SearchField label="협력사">
          <Input value={supplierName} onChange={(e) => setSupplierName(e.target.value)} className="w-[150px]" />
        </SearchField>
      </SearchForm>

      <DataGrid columns={columns} data={data} showCheckbox
        onSelectionChange={setSelectedRows} />
    </div>
  );
}
