"use client";

import { useState, useCallback, useEffect } from "react";
import { SearchForm, SearchField } from "@/components/layout/search-form";
import { Button } from "@/components/ui/button";
import { CodeSelect } from "@/components/ui/code-select";

// csMgmt/csChartList.jsp 대응 - CS 차트관리
export default function CsChartPage() {
  const [year, setYear] = useState(new Date().getFullYear().toString());
  const [productCode, setProductCode] = useState("");
  const [chartData, setChartData] = useState<Record<string, unknown>[]>([]);

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

  // 페이지 진입 시 자동 로드
  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" 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="제품구분">
          <CodeSelect codeId="PRODUCT_TYPE" value={productCode} onChange={setProductCode} className="w-[130px]" />
        </SearchField>
      </SearchForm>

      <div className="bg-white rounded-lg border border-gray-200 p-6" style={{ height: "calc(100vh - 350px)" }}>
        {chartData.length > 0 ? (
          <div className="text-center text-gray-500">
            {/* TODO: Chart rendering - integrate with chart library */}
            <p className="text-sm">차트 데이터 {chartData.length}건 로드됨</p>
            <p className="text-xs text-gray-400 mt-2">차트 라이브러리 연동 후 표시됩니다.</p>
          </div>
        ) : (
          <div className="flex items-center justify-center h-full text-gray-400">
            조회 버튼을 클릭하여 차트 데이터를 로드하세요.
          </div>
        )}
      </div>
    </div>
  );
}
