"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";

// productionplanning/processperformanceList.jsp 대응 - 생산관리_공정실적관리
function openPopup(url: string, name: string, w: number, h: number) {
  const left = (window.screen.width - w) / 2;
  const top = (window.screen.height - h) / 2;
  window.open(url, name, `width=${w},height=${h},left=${left},top=${top},scrollbars=yes,resizable=yes`);
}

export default function ProductionProcessPage() {
  const [year, setYear] = useState(new Date().getFullYear().toString());
  const [projectNo, setProjectNo] = useState("");
  const [customerObjid, setCustomerObjid] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);

  const openProjectForm = (objId: string) =>
    openPopup(`/project/modify?objId=${encodeURIComponent(objId)}`, "projectForm", 520, 650);
  const openAssemblyPopup = (row: Record<string, unknown>) =>
    openPopup(
      `/production/assembly-popup?objId=${encodeURIComponent(String(row.OBJID || ""))}`,
      "assemblyList", 1300, 800
    );

  const columns: GridColumn[] = [
    {
      title: "프로젝트정보",
      columns: [
        { title: "프로젝트번호", field: "PROJECT_NO", width: 120, hozAlign: "center", frozen: true,
          cellClick: (row) => openProjectForm(String(row.CONTRACT_OBJID)) },
        { title: "고객사", field: "CUSTOMER_NAME", width: 140, hozAlign: "left" },
        { title: "당사프로젝트명", field: "PROJECT_NAME", width: 250, hozAlign: "left" },
        { title: "요청납기일", field: "DUE_DATE", width: 100, hozAlign: "center" },
        { title: "셋업지", field: "SETUP", width: 110, hozAlign: "center" },
        { title: "PM", field: "PM_USER_NAME", width: 100, hozAlign: "center" },
      ],
    },
    {
      title: "조립(제작)",
      columns: [
        {
          title: "E-BOM/구매 BOM",
          columns: [
            { title: "유닛명", field: "UNIT_NAME", width: 270, hozAlign: "left" },
          ],
        },
        {
          title: "생산BOM",
          columns: [
            { title: "조립총수", field: "BOM_CNT", width: 90, hozAlign: "right", formatter: "money",
              cellClick: (row) => openAssemblyPopup(row) },
            { title: "조립품수", field: "ASSING_CNT", width: 90, hozAlign: "right", formatter: "money",
              cellClick: (row) => openAssemblyPopup(row) },
            { title: "공정율(%)", field: "AS_RATE", width: 90, hozAlign: "right" },
          ],
        },
        {
          title: "작업공수(H)",
          columns: [
            { title: "투입공수", field: "TOTAL_SUM", width: 90, hozAlign: "right", formatter: "money" },
            { title: "자사", field: "INSOURCING_SUM", width: 80, hozAlign: "right", formatter: "money" },
            { title: "외주", field: "OUTSOURCING_SUM", width: 80, hozAlign: "right", formatter: "money" },
          ],
        },
      ],
    },
  ];

  const fetchData = useCallback(async () => {
    const res = await fetch("/api/production/process", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ year, project_no: projectNo, customer_objid: customerObjid }),
    });
    if (res.ok) {
      const json = await res.json();
      setData(json.RESULTLIST || []);
    }
  }, [year, projectNo, customerObjid]);

  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" 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">
            <option value="">선택</option>
            {Array.from({ length: 5 }, (_, i) => new Date().getFullYear() - i).map((y) => (
              <option key={y} value={y}>{y}</option>
            ))}
          </select>
        </SearchField>
        <SearchField label="프로젝트번호">
          <Input value={projectNo} onChange={(e) => setProjectNo(e.target.value)} className="w-[180px]" />
        </SearchField>
        <SearchField label="고객사">
          <CodeSelect codeId="CUSTOMER" value={customerObjid} onChange={setCustomerObjid} className="w-[160px]" />
        </SearchField>
      </SearchForm>

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