"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 { CodeSelect } from "@/components/ui/code-select";

// scm/scmOrderList.jsp 대응 - SCM 발주관리
export default function ScmOrderPage() {
  const [year, setYear] = useState(new Date().getFullYear().toString());
  const [purchaseOrderNo, setPurchaseOrderNo] = useState("");
  const [customerName, setCustomerName] = useState("");
  const [projectNo, setProjectNo] = useState("");
  const [statusCode, setStatusCode] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);
  const [selectedRows, setSelectedRows] = useState<Record<string, unknown>[]>([]);

  const columns: GridColumn[] = [
    { title: "발주No", field: "PURCHASE_ORDER_NO", width: 140, hozAlign: "left",
      cellClick: (row) => window.open(`/scm/order/form?objId=${row.OBJID}`, "scmOrderDetail", "width=1100,height=700") },
    { title: "복합마스터", field: "MULTI_MASTER_YN", width: 90, hozAlign: "center" },
    { title: "영업담당", field: "SALES_MNG_USER_NAME", width: 90, hozAlign: "center" },
    { title: "등록일", field: "REGDATE", width: 100, hozAlign: "center" },
    { title: "고객사", field: "CUSTOMER_NAME", width: 150, hozAlign: "left" },
    { title: "프로젝트번호", field: "PROJECT_NO", width: 120, hozAlign: "left" },
    { title: "유닛명", field: "UNIT_NAME", width: 120, hozAlign: "left" },
    { title: "발주명", field: "TITLE", width: 200, hozAlign: "left" },
    { title: "납기일", field: "DELIVERY_DATE", width: 100, hozAlign: "center" },
    { title: "납품장소", field: "DELIVERY_PLACE_NAME", width: 120, hozAlign: "left" },
    { title: "파트수", field: "PART_CNT", width: 70, hozAlign: "right" },
    { title: "실발주수", field: "REAL_ORDER_CNT", width: 80, hozAlign: "right" },
    { title: "상태", field: "STATUS_NAME", width: 80, hozAlign: "center" },
    { title: "입고수", field: "ARRIVAL_CNT", width: 70, hozAlign: "right" },
    { title: "영업상태", field: "SALES_STATUS", width: 80, hozAlign: "center" },
    { title: "입고수량", field: "RECEIPT_QTY", width: 80, hozAlign: "right" },
    { title: "미납수량", field: "NON_DELIVERY_QTY", width: 80, hozAlign: "right" },
    { title: "불량수량", field: "ERROR_QTY", width: 80, hozAlign: "right" },
    { title: "발행일", field: "ISSUANCE_DATE", width: 100, hozAlign: "center" },
  ];

  const fetchData = useCallback(async () => {
    const res = await fetch("/api/scm/order", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        year,
        purchase_order_no: purchaseOrderNo,
        customer_name: customerName,
        project_no: projectNo,
        status_code: statusCode,
      }),
    });
    if (res.ok) {
      const json = await res.json();
      setData(json.RESULTLIST || []);
    }
  }, [year, purchaseOrderNo, customerName, projectNo, statusCode]);

  const handleReceipt = async () => {
    if (selectedRows.length === 0) {
      alert("접수할 항목을 선택하세요.");
      return;
    }
    // 선택 건들 일괄 접수 처리 (reception_status='reception')
    const objIds = selectedRows.map((r) => String(r.OBJID));
    const res = await fetch("/api/scm/order/receipt", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ objIds }),
    });
    const json = await res.json();
    if (json.success) {
      alert(json.message || "접수 완료");
      fetchData();
    } else {
      alert(json.message || "접수 실패");
    }
  };

  const handleArrivalPlan = () => {
    if (selectedRows.length === 0) {
      alert("입고계획을 등록할 항목을 선택하세요.");
      return;
    }
    const row = selectedRows[0];
    const w = 900, h = 600;
    const left = (window.screen.width - w) / 2, top = (window.screen.height - h) / 2;
    window.open(`/scm/order/arrival-plan?objId=${row.OBJID}`, "arrivalPlan",
      `width=${w},height=${h},left=${left},top=${top}`);
  };

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

  return (
    <div>
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-bold text-gray-800">SCM 발주관리</h2>
        <div className="flex gap-2">
          <Button size="sm" onClick={handleReceipt}>접수</Button>
          <Button size="sm" variant="secondary" onClick={handleArrivalPlan}>입고계획등록</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={purchaseOrderNo} onChange={(e) => setPurchaseOrderNo(e.target.value)} className="w-[140px]" />
        </SearchField>
        <SearchField label="고객사">
          <Input value={customerName} onChange={(e) => setCustomerName(e.target.value)} className="w-[150px]" />
        </SearchField>
        <SearchField label="프로젝트번호">
          <Input value={projectNo} onChange={(e) => setProjectNo(e.target.value)} className="w-[140px]" />
        </SearchField>
        <SearchField label="상태">
          <CodeSelect codeId="SCM_ORDER_STATUS" value={statusCode} onChange={setStatusCode} className="w-[120px]" />
        </SearchField>
      </SearchForm>

      <DataGrid
        columns={columns}
        data={data}
        showCheckbox

        onSelectionChange={setSelectedRows}
      />
    </div>
  );
}
