"use client";

// 개발관리 > 설계변경 리스트 (M5, read-only) — wace partMngHisList.jsp 1:1
// 그리드: part_mng_history 16셀
// 검색: 8 필드 (1차) — Year/contract_objid/part_no/part_name/eo_start~end/change_type/change_option/part_type
// 참조: docs/migration/development/03-eo-history.md

import React, { useCallback, useEffect, useMemo, useState } from "react";
import { Input } from "@/components/ui/input";
import { toast } from "sonner";
import { DataGrid, DataGridColumn } from "@/components/common/DataGrid";
import { CommCodeSelect } from "@/components/common/CommCodeSelect";
import { SmartSelect, SmartSelectOption } from "@/components/common/SmartSelect";
import { PageHeader } from "@/components/common/PageHeader";
import { CompactFilterBar, CompactFilterField, CompactDateRange } from "@/components/common/CompactFilterBar";
import { devEoHistoryApi, EoHistoryListFilter, EoHistoryRow } from "@/lib/api/devEoHistory";
import { PartHisDetailDialog } from "@/components/development/PartHisDetailDialog";
import { exportToExcel } from "@/lib/utils/excelExport";

// comm_code 그룹 (vexplor_rps)
const GROUP_PART_TYPE = "0000062";
// change_type/change_option은 wace 운영판 그룹 ID가 명확하지 않으므로 text input으로 우선 운영.
// (시드 후 그룹 ID 확인되면 SmartSelect 전환)

const YEAR_OPTIONS: SmartSelectOption[] = (() => {
  const cur = new Date().getFullYear();
  const arr: SmartSelectOption[] = [];
  for (let y = cur + 4; y >= cur - 8; y--) arr.push({ code: String(y), label: String(y) });
  return arr;
})();

const GRID_COLUMNS: DataGridColumn[] = [
  { key: "eo_no", label: "EO No", width: "w-[110px]", frozen: true },
  { key: "project_no", label: "프로젝트번호", width: "w-[140px]" },
  { key: "project_name", label: "프로젝트명", width: "w-[180px]" },
  { key: "unit_name", label: "유닛명", width: "w-[160px]" },
  { key: "parent_part_info", label: "모품번", width: "w-[160px]" },
  { key: "part_no_disp", label: "품번", width: "w-[160px]" },
  { key: "part_name_disp", label: "품명", minWidth: "min-w-[180px]" },
  { key: "qty", label: "수량", width: "w-[95px]", align: "right", formatNumber: true },
  { key: "qty_temp", label: "변경수량", width: "w-[115px]", align: "right", formatNumber: true },
  { key: "change_type_name", label: "EO구분", width: "w-[115px]", align: "center" },
  { key: "change_option_name", label: "EO사유", width: "w-[115px]", align: "center" },
  { key: "revision_disp", label: "Revision", width: "w-[115px]", align: "center" },
  { key: "eo_date", label: "EO Date", width: "w-[110px]", align: "center" },
  { key: "part_type_name", label: "PART구분", width: "w-[115px]", align: "center" },
  { key: "writer_name", label: "담당자", width: "w-[115px]", align: "center" },
  { key: "his_reg_date_title", label: "실행일", width: "w-[115px]", align: "center" },
];

const EMPTY_FILTER: EoHistoryListFilter = {
  Year: "", contract_objid: "",
  part_no: "", part_name: "",
  change_option: "", change_type: "", part_type: "",
  eo_start_date: "", eo_end_date: "",
  page: 1, page_size: 50,
};

export default function EoHistoryPage() {
  const [rows, setRows] = useState<EoHistoryRow[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [filter, setFilter] = useState<EoHistoryListFilter>(EMPTY_FILTER);

  const [detailOpen, setDetailOpen] = useState(false);
  const [detailObjid, setDetailObjid] = useState<string | null>(null);

  const fetchList = useCallback(async (override?: Partial<EoHistoryListFilter>) => {
    setLoading(true);
    try {
      const f = { ...filter, ...override };
      const res = await devEoHistoryApi.list(f);
      // DataGrid row 키 — objid 없을 수 있어 인덱스 fallback (id 누락 시 모든 행이 selected 로 잡힘)
      const list = (res.rows ?? []).map((r, i) => ({ ...r, id: (r as any).objid ?? `eo-${i}` }));
      setRows(list as any);
      setTotal(res.total ?? 0);
    } catch (e: any) {
      toast.error(e?.response?.data?.message ?? e?.message ?? "조회 실패");
    } finally {
      setLoading(false);
    }
  }, [filter]);

  useEffect(() => { fetchList(); /* eslint-disable-next-line */ }, []);

  // EO_NO 셀 클릭 → 상세 다이얼로그
  const columns = useMemo(
    () => GRID_COLUMNS.map((c) =>
      c.key === "eo_no"
        ? { ...c, onClick: (row: any) => { setDetailObjid(row.objid); setDetailOpen(true); } }
        : c,
    ),
    [],
  );

  // ─── 하단 통계 ──────────────────────────────────────────────
  // 이력 건수(총·페이지) / 수량·변경수량 합계
  const eoSummary = useMemo(() => {
    const pageCount = rows.length;
    const qtySum    = rows.reduce((acc, r: any) => acc + Number(r.qty || 0), 0);
    const qtyTemp   = rows.reduce((acc, r: any) => acc + Number(r.qty_temp || 0), 0);
    const intFmt = (n: number) => n.toLocaleString();
    return [
      { label: "전체 건수", value: intFmt(total), suffix: "건" },
      { label: "페이지 건수", value: intFmt(pageCount), suffix: "건" },
      { label: "수량 합계", value: intFmt(qtySum) },
      { label: "변경수량 합계", value: intFmt(qtyTemp) },
    ];
  }, [rows, total]);

  return (
    <div className="flex h-full flex-col overflow-hidden p-2 gap-2">
      <PageHeader
        loading={loading}
        onSearch={() => fetchList()}
        onReset={() => { setFilter(EMPTY_FILTER); fetchList(EMPTY_FILTER); }}
      />

      <CompactFilterBar totalText={<>총 {total.toLocaleString()}건 (read-only)</>}>
        <CompactFilterField label="년도" width={100}>
          <SmartSelect
            options={YEAR_OPTIONS}
            value={filter.Year ?? ""}
            onValueChange={(v) => setFilter({ ...filter, Year: v })}
            placeholder="전체"
          />
        </CompactFilterField>
        <CompactFilterField label="프로젝트 OBJID" width={180}>
          <Input value={filter.contract_objid ?? ""}
                 onChange={(e) => setFilter({ ...filter, contract_objid: e.target.value })}
                 placeholder="project_mgmt.objid" />
        </CompactFilterField>
        <CompactFilterField label="품번" width={140}>
          <Input value={filter.part_no ?? ""}
                 onChange={(e) => setFilter({ ...filter, part_no: e.target.value })}
                 placeholder="part_no LIKE" />
        </CompactFilterField>
        <CompactFilterField label="품명" width={150}>
          <Input value={filter.part_name ?? ""}
                 onChange={(e) => setFilter({ ...filter, part_name: e.target.value })}
                 placeholder="part_name LIKE" />
        </CompactFilterField>
        <CompactFilterField label="EO Date" width={280}>
          <CompactDateRange
            from={filter.eo_start_date ?? ""}
            setFrom={(v) => setFilter({ ...filter, eo_start_date: v })}
            to={filter.eo_end_date ?? ""}
            setTo={(v) => setFilter({ ...filter, eo_end_date: v })}
          />
        </CompactFilterField>
        <CompactFilterField label="PART구분" width={140}>
          <CommCodeSelect groupId={GROUP_PART_TYPE}
                          value={filter.part_type ?? ""}
                          onValueChange={(v) => setFilter({ ...filter, part_type: v })} />
        </CompactFilterField>
        <CompactFilterField label="EO구분 code_id" width={140}>
          <Input value={filter.change_type ?? ""}
                 onChange={(e) => setFilter({ ...filter, change_type: e.target.value })} />
        </CompactFilterField>
        <CompactFilterField label="EO사유 code_id" width={140}>
          <Input value={filter.change_option ?? ""}
                 onChange={(e) => setFilter({ ...filter, change_option: e.target.value })} />
        </CompactFilterField>
      </CompactFilterBar>

      <DataGrid
        columns={columns}
        data={rows}
        loading={loading}
        showRowNumber
        emptyMessage="설계변경 이력이 없습니다."
        gridId="development-eo-history"
        showColumnSettings
        paginationStyle="range"
        pageSizeOptions={[10, 15, 20, 50, 100, 200, 500]}
        serverPaging
        serverPage={filter.page ?? 1}
        serverPageSize={filter.page_size ?? 50}
        serverTotalItems={total}
        onPageChange={(p) => { setFilter(f => ({ ...f, page: p })); fetchList({ page: p }); }}
        onPageSizeChange={(n) => { setFilter(f => ({ ...f, page: 1, page_size: n })); fetchList({ page: 1, page_size: n }); }}
        summaryStats={eoSummary}
        systemColumnKeys={["writer_name", "his_reg_date_title"]}
        onRefresh={() => fetchList()}
        onDownload={() => {
          if (rows.length === 0) { toast.info("내보낼 데이터가 없습니다."); return; }
          const exportRows = rows.map((r: any) => {
            const out: Record<string, any> = {};
            GRID_COLUMNS.forEach((col) => { out[col.label] = r[col.key] ?? ""; });
            return out;
          });
          exportToExcel(exportRows, "설계변경_리스트.xlsx", "설계변경_리스트");
        }}
        showChart
      />

      <PartHisDetailDialog
        open={detailOpen}
        onOpenChange={setDetailOpen}
        objid={detailObjid}
      />
    </div>
  );
}

