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

// customerMng/customerServiceList.jsp 대응 - CS관리
export default function CsPage() {
  const [year, setYear] = useState(new Date().getFullYear().toString());
  const [customerName, setCustomerName] = useState("");
  const [data, setData] = useState<Record<string, unknown>[]>([]);

  const columns: GridColumn[] = [
    { title: "접수번호", field: "CS_NO", width: 120,
      cellClick: (row) => window.open(`/cs/manage/form?objId=${row.OBJID}`, "csDetail", "width=900,height=700") },
    { title: "고객사", field: "CUSTOMER_NAME", width: 150, hozAlign: "left" },
    { title: "제품명", field: "PRODUCT_NAME", width: 150, hozAlign: "left" },
    { title: "접수일", field: "RECEIPT_DATE", width: 100, hozAlign: "center" },
    { title: "유형", field: "CS_TYPE_NAME", width: 100, hozAlign: "center" },
    { title: "내용", field: "DESCRIPTION", hozAlign: "left" },
    { title: "상태", field: "STATUS_NAME", width: 80, hozAlign: "center" },
    { title: "담당자", field: "CHARGER_NAME", width: 90, hozAlign: "center" },
    { title: "완료일", field: "COMPLETE_DATE", width: 100, hozAlign: "center" },
  ];

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

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

  return (
    <div>
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-bold text-gray-800">CS 관리</h2>
        <div className="flex gap-2">
          <Button size="sm" onClick={() => window.open("/cs/manage/form", "csForm", "width=900,height=700")}>등록</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={customerName} onChange={(e) => setCustomerName(e.target.value)} className="w-[150px]" />
        </SearchField>
      </SearchForm>
      <DataGrid columns={columns} data={data} />
    </div>
  );
}
