"use client";

import { useState, useCallback, useEffect, useMemo } from "react";
import { DataGrid, type GridColumn } from "@/components/grid/data-grid";
import { SearchForm, SearchField } from "@/components/layout/search-form";
import { Button } from "@/components/ui/button";
import { SearchableCodeSelect } from "@/components/ui/searchable-code-select";
import { SearchableSelect } from "@/components/ui/searchable-select";

interface DynColumn {
  GROUP_SEQ: number;
  GROUP_CNT: number;
  GROUP_NAME: string;
  PARENT_CODE_ID: string;
  CODE_ID: string;
  NAME: string;
  COL_NAME: string;
}

// asList_CS.jsp 대응 - CS관리_현황 (제품×프로젝트 대시보드)
export default function CsStatusPage() {
  const [year, setYear] = useState(new Date().getFullYear().toString());
  const [productCd, setProductCd] = useState("");
  const [projectNo, setProjectNo] = useState("");
  const [warranty, setWarranty] = useState("");
  const [csCategory, setCsCategory] = useState("");
  const [categoryH, setCategoryH] = useState("");

  const [projectOpts, setProjectOpts] = useState<{ value: string; label: string }[]>([]);
  const [categoryHOpts, setCategoryHOpts] = useState<{ value: string; label: string }[]>([]);
  const [data, setData] = useState<Record<string, unknown>[]>([]);
  const [dynColumns, setDynColumns] = useState<DynColumn[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetch("/api/common/project-list", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" })
      .then((r) => r.json())
      .then((j) =>
        setProjectOpts(
          (j.RESULTLIST || []).map((r: Record<string, unknown>) => ({
            value: String(r.OBJID),
            label: String(r.LABEL || r.PROJECT_NO || r.OBJID),
          }))
        )
      )
      .catch(() => setProjectOpts([]));
  }, []);

  // cs_category(0000970) 선택 시 유형(category_h) 옵션 로드
  useEffect(() => {
    if (!csCategory) {
      setCategoryHOpts([]);
      setCategoryH("");
      return;
    }
    fetch("/api/common/code-list", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ codeId: csCategory }),
    })
      .then((r) => r.json())
      .then((j) =>
        setCategoryHOpts(
          (j.data || []).map((r: Record<string, unknown>) => ({
            value: String(r.code_id || r.CODE_ID),
            label: String(r.code_name || r.CODE_NAME),
          }))
        )
      )
      .catch(() => setCategoryHOpts([]));
  }, [csCategory]);

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/cs/status", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          Year: year,
          product_cd: productCd,
          project_no: projectNo,
          warranty,
          cs_category: csCategory,
          category_h: categoryH,
        }),
      });
      if (res.ok) {
        const json = await res.json();
        setData(json.RESULTLIST || []);
        setDynColumns(json.COLUMN_LIST || []);
      }
    } finally {
      setLoading(false);
    }
  }, [year, productCd, projectNo, warranty, csCategory, categoryH]);

  useEffect(() => { fetchData(); }, [fetchData]);

  const columns: GridColumn[] = useMemo(() => {
    // 동적 컬럼 → GROUP_NAME(2nd-level 부모코드명) 기준으로 묶고, leaf는 NAME 사용
    const groupMap = new Map<string, DynColumn[]>();
    const groupOrder: string[] = [];
    dynColumns.forEach((c) => {
      const key = `${c.PARENT_CODE_ID}::${c.GROUP_NAME}`;
      if (!groupMap.has(key)) {
        groupMap.set(key, []);
        groupOrder.push(key);
      }
      groupMap.get(key)!.push(c);
    });

    const dynGroupColumns: GridColumn[] = groupOrder.map((key) => {
      const group = groupMap.get(key)!;
      return {
        title: group[0].GROUP_NAME || "유형",
        columns: group.map((c) => ({
          title: c.NAME,
          field: c.COL_NAME,
          width: 90,
          hozAlign: "right",
          headerHozAlign: "center",
          formatter: "money",
        })),
      };
    });

    // 유형 최상위 묶음 (있을 때만)
    const categoryWrapper: GridColumn[] = dynGroupColumns.length
      ? [{ title: "유형", columns: dynGroupColumns }]
      : [];

    return [
      { title: "제품구분", field: "PRODUCT_NAME", width: 140, hozAlign: "left" },
      { title: "프로젝트번호", field: "PROJECT_NO", width: 130, hozAlign: "left" },
      {
        title: "유상",
        columns: [
          { title: "건수", field: "WARRANTY1", width: 80, hozAlign: "right", headerHozAlign: "center", formatter: "money" },
          { title: "발생비용", field: "COST1", width: 110, hozAlign: "right", headerHozAlign: "center", formatter: "money" },
        ],
      },
      {
        title: "무상",
        columns: [
          { title: "건수", field: "WARRANTY2", width: 80, hozAlign: "right", headerHozAlign: "center", formatter: "money" },
          { title: "발생비용", field: "COST2", width: 110, hozAlign: "right", headerHozAlign: "center", formatter: "money" },
        ],
      },
      ...categoryWrapper,
    ];
  }, [dynColumns]);

  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-[110px] 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="제품구분">
          <SearchableCodeSelect codeId="0000001" value={productCd} onChange={setProductCd} className="w-[150px]" />
        </SearchField>
        <SearchField label="프로젝트번호">
          <SearchableSelect options={projectOpts} value={projectNo} onChange={setProjectNo} className="w-[220px]" />
        </SearchField>
        <SearchField label="유/무상">
          <SearchableCodeSelect codeId="0000156" value={warranty} onChange={setWarranty} className="w-[120px]" />
        </SearchField>
        <SearchField label="CS구분">
          <SearchableCodeSelect codeId="0000970" value={csCategory} onChange={setCsCategory} className="w-[150px]" />
        </SearchField>
        <SearchField label="유형">
          <SearchableSelect options={categoryHOpts} value={categoryH} onChange={setCategoryH} className="w-[150px]" />
        </SearchField>
      </SearchForm>

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