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

// project/projectList.jsp 대응 - 프로젝트관리
export default function ProjectPage() {
  const [year, setYear] = useState(new Date().getFullYear().toString());
  const [projectNo, setProjectNo] = useState("");
  const [projectName, setProjectName] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);

  const columns: GridColumn[] = [
    { title: "프로젝트번호", field: "PROJECT_NO", width: 130,
      cellClick: (row) => window.open(`/sales/contract/form?objId=${row.OBJID}`, "projectDetail", "width=1200,height=900") },
    { title: "프로젝트명", field: "PROJECT_NAME", width: 250, hozAlign: "left" },
    { title: "고객사", field: "CUSTOMER_NAME", width: 150, hozAlign: "left" },
    { title: "제품명", field: "PRODUCT_NAME", width: 150, hozAlign: "left" },
    { title: "제조공장", field: "MANUFACTURE_PLANT_NAME", width: 120, hozAlign: "center" },
    { title: "상태", field: "STATUS", width: 80, hozAlign: "center" },
    { title: "진행율", field: "TOTAL_RATE", width: 80, hozAlign: "center",
      formatter: (_cell, row) => `${row.TOTAL_RATE || 0}%` },
    { title: "PM", field: "PM_NAME", width: 90, hozAlign: "center" },
    { title: "시작일", field: "START_DATE", width: 100, hozAlign: "center" },
    { title: "종료일", field: "END_DATE", width: 100, hozAlign: "center" },
  ];

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

  // 페이지 진입 시 자동 로드
  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">
            {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-[130px]" />
        </SearchField>
        <SearchField label="프로젝트명">
          <Input value={projectName} onChange={(e) => setProjectName(e.target.value)} className="w-[200px]" />
        </SearchField>
      </SearchForm>

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