"use client";

// 진행관리 (wace projectMgmtWbsList3.jsp + projectMgmtWbsGridList 1:1 이식)
// 원본:
//   - JSP: /Users/jhj/wace_plm/WebContent/WEB-INF/view/project/projectMgmtWbsList3.jsp (349줄)
//   - 매퍼: wace_plm/src/com/pms/mapper/project.xml:3854 projectMgmtWbsGridList
// GAP: docs/migration/project/00-gap.md
//
// 그리드: 8그룹 18셀 평탄화 (DataGrid가 그룹 헤더 미지원 → 라벨 prefix로 표현)
// 검색폼: 11필드 (1행 6 + 2행 5)
// 행 클릭: P1.5에서 영업관리 OrderRegistDialog 재사용 검토 — 현재 미연결

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 { CustomerSelect } from "@/components/common/CustomerSelect";
import { PartSelect } from "@/components/common/PartSelect";
import { SmartSelect, SmartSelectOption } from "@/components/common/SmartSelect";
import { PageHeader } from "@/components/common/PageHeader";
import { CompactFilterBar, CompactFilterField, CompactDateRange } from "@/components/common/CompactFilterBar";
import { ProjectInfoDialog, ProjectInfoData } from "@/components/project/ProjectInfoDialog";
import { projectMgmtApi, ProgressListFilter, ProgressRow } from "@/lib/api/projectMgmt";
import { exportToExcel } from "@/lib/utils/excelExport";

// 진행관리 row → 정규화된 ProjectInfoData 매핑
const toProjectInfo = (r: ProgressRow): ProjectInfoData => ({
  orderType: r.category_name,
  productType: r.product_name,
  area: r.area_name,
  customer: r.customer_name,
  paidType: r.free_of_charge,
  regDate: r.reg_date,
  currency: r.contract_currency_name,
  exchangeRate: r.exchange_rate,
  partNo: r.product_item_code,
  partName: r.product_item_name,
  serialNo: r.serial_no,
  reqDelDate: r.req_del_date,
  customerRequest: r.customer_request,
  returnReason: r.return_reason_name,
});

// wace projectMgmtWbsList3.jsp 컬럼 정의 1:1 (8그룹 → 평탄화, 그룹명은 라벨 prefix)
const GRID_COLUMNS: DataGridColumn[] = [
  { key: "project_no", label: "프로젝트번호", width: "w-[160px]", frozen: true },
  // 프로젝트정보 그룹
  { key: "category_name", label: "주문유형", width: "w-[115px]", align: "center" },
  { key: "product_name", label: "제품구분", width: "w-[115px]", align: "left" },
  { key: "area_name", label: "국내/해외", width: "w-[115px]", align: "center" },
  { key: "reg_date", label: "접수일", width: "w-[115px]", align: "center" },
  { key: "customer_name", label: "고객사", width: "w-[140px]" },
  { key: "free_of_charge", label: "유/무상", width: "w-[100px]", align: "center" },
  { key: "product_item_code", label: "품번", width: "w-[150px]" },
  { key: "product_item_name", label: "품명", width: "w-[180px]" },
  { key: "serial_no", label: "S/N", width: "w-[150px]" },
  { key: "contract_qty", label: "수주수량", width: "w-[115px]", align: "right", formatNumber: true },
  { key: "req_del_date", label: "요청납기", width: "w-[115px]", align: "center" },
  // 설계
  { key: "ebom_status", label: "E-BOM", width: "w-[115px]", align: "center" },
  // 생산관리
  { key: "mbom_status", label: "M-BOM", width: "w-[115px]", align: "center" },
  // 구매
  { key: "order_date", label: "발주일", width: "w-[115px]", align: "center" },
  { key: "receiving_rate", label: "입고율", width: "w-[100px]", align: "right" },
  // 생산
  { key: "production_team_12", label: "제조1,2팀", width: "w-[120px]", align: "center" },
  { key: "production_team_3", label: "제조3팀", width: "w-[115px]", align: "center" },
  // 장비
  { key: "assembly", label: "조립", width: "w-[100px]", align: "center" },
  { key: "verification", label: "검증", width: "w-[100px]", align: "center" },
  // 출하
  { key: "shipment_date", label: "출하일", width: "w-[115px]", align: "center" },
];

const CATEGORY_GROUP = "0000167"; // 주문유형
const PRODUCT_GROUP = "0000001";  // 제품구분

// wace L229: 시스템년도 ±4 (운영판은 sysYear-4 ~ sysYear). RPS는 sysYear±4로 여유.
const YEAR_OPTIONS: SmartSelectOption[] = (() => {
  const cur = new Date().getFullYear();
  const arr: SmartSelectOption[] = [];
  for (let y = cur + 4; y >= cur - 4; y--) arr.push({ code: String(y), label: String(y) });
  return arr;
})();

const AREA_OPTIONS: SmartSelectOption[] = [
  { code: "국내", label: "국내" },
  { code: "해외", label: "해외" },
];

const PAID_OPTIONS: SmartSelectOption[] = [
  { code: "유상", label: "유상" },
  { code: "무상", label: "무상" },
];

const EMPTY_FILTER: ProgressListFilter = {
  Year: "", project_nos: "", category_cd: "", customer_objid: "", product: "",
  contract_start_date: "", contract_end_date: "",
  area_cd: "", free_of_charge: "",
  search_partObjId: "", serial_no: "",
};

export default function ProjectProgressPage() {
  const [rows, setRows] = useState<ProgressRow[]>([]);
  const [loading, setLoading] = useState(false);
  const [filter, setFilter] = useState<ProgressListFilter>(EMPTY_FILTER);
  const [projectNoOptions, setProjectNoOptions] = useState<SmartSelectOption[]>([]);

  // wace `fn_openSaleRegPopup(PROJECT_NO, "detail")` 대응 — PROJECT_NO 셀 클릭 시 프로젝트 정보 다이얼로그
  const [infoOpen, setInfoOpen] = useState(false);
  const [infoData, setInfoData] = useState<ProjectInfoData | null>(null);

  // GRID_COLUMNS의 project_no 셀에만 onClick 주입 (DataGrid 컬럼별 onClick 패턴)
  const columns = useMemo(
    () => GRID_COLUMNS.map((col) =>
      col.key === "project_no"
        ? { ...col, onClick: (row: any) => { setInfoData(toProjectInfo(row as ProgressRow)); setInfoOpen(true); } }
        : col,
    ),
    [],
  );

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

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

  // 프로젝트번호 셀렉트 옵션 (wace common.getCusProjectNoList 대응)
  useEffect(() => {
    projectMgmtApi.projectNoOptions()
      .then((opts) => setProjectNoOptions(opts.map((o) => ({ code: o.value, label: o.label }))))
      .catch(() => {});
  }, []);

  const handleReset = () => {
    setFilter(EMPTY_FILTER);
    setTimeout(() => fetchList(), 0);
  };

  // ─── 하단 통계 ──────────────────────────────────────────────
  // 프로젝트 건수 / 수주수량 합계 / 입고율 평균
  const progressSummary = useMemo(() => {
    const count = rows.length;
    const qtySum = rows.reduce((acc, r) => acc + Number(r.contract_qty || 0), 0);
    // 입고율은 "85%" 같은 문자열 가능 → 숫자만 추출
    const rateNums = rows
      .map((r) => parseFloat(String((r as any).receiving_rate ?? "").replace(/[^0-9.]/g, "")))
      .filter((n) => !Number.isNaN(n));
    const rateAvg = rateNums.length === 0 ? 0 : rateNums.reduce((a, b) => a + b, 0) / rateNums.length;
    const intFmt = (n: number) => n.toLocaleString();
    return [
      { label: "프로젝트 건수", value: intFmt(count), suffix: "건" },
      { label: "수주수량 합계", value: intFmt(qtySum) },
      { label: "입고율 평균", value: rateAvg.toFixed(1), suffix: "%" },
    ];
  }, [rows]);

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

      <CompactFilterBar totalText={<>총 {rows.length.toLocaleString()}건</>}>
        <CompactFilterField label="년도" width={100}>
          <SmartSelect
            options={YEAR_OPTIONS}
            value={filter.Year ?? ""}
            onValueChange={(v) => setFilter({ ...filter, Year: v })}
            placeholder="전체"
          />
        </CompactFilterField>
        <CompactFilterField label="프로젝트번호" width={160}>
          <SmartSelect
            options={projectNoOptions}
            value={filter.project_nos ?? ""}
            onValueChange={(v) => setFilter({ ...filter, project_nos: v })}
            placeholder="전체"
          />
        </CompactFilterField>
        <CompactFilterField label="주문유형" width={130}>
          <CommCodeSelect
            groupId={CATEGORY_GROUP}
            value={filter.category_cd ?? ""}
            onValueChange={(v) => setFilter({ ...filter, category_cd: v })}
          />
        </CompactFilterField>
        <CompactFilterField label="고객사" width={160}>
          <CustomerSelect
            value={filter.customer_objid ?? ""}
            onValueChange={(v) => setFilter({ ...filter, customer_objid: v })}
          />
        </CompactFilterField>
        <CompactFilterField label="제품구분" width={130}>
          <CommCodeSelect
            groupId={PRODUCT_GROUP}
            value={filter.product ?? ""}
            onValueChange={(v) => setFilter({ ...filter, product: v })}
          />
        </CompactFilterField>
        <CompactFilterField label="국내/해외" width={100}>
          <SmartSelect
            options={AREA_OPTIONS}
            value={filter.area_cd ?? ""}
            onValueChange={(v) => setFilter({ ...filter, area_cd: v })}
            placeholder="전체"
          />
        </CompactFilterField>
        <CompactFilterField label="유/무상" width={100}>
          <SmartSelect
            options={PAID_OPTIONS}
            value={filter.free_of_charge ?? ""}
            onValueChange={(v) => setFilter({ ...filter, free_of_charge: v })}
            placeholder="전체"
          />
        </CompactFilterField>
        <CompactFilterField label="품번" width={130}>
          <PartSelect
            mode="partNo"
            value={filter.search_partObjId ?? ""}
            onValueChange={(v) => setFilter({ ...filter, search_partObjId: v })}
          />
        </CompactFilterField>
        <CompactFilterField label="품명" width={150}>
          <PartSelect
            mode="partName"
            value={filter.search_partObjId ?? ""}
            onValueChange={(v) => setFilter({ ...filter, search_partObjId: v })}
          />
        </CompactFilterField>
        <CompactFilterField label="S/N" width={120}>
          <Input
            value={filter.serial_no ?? ""}
            onChange={(e) => setFilter({ ...filter, serial_no: e.target.value })}
            placeholder="S/N LIKE"
          />
        </CompactFilterField>
        <CompactFilterField label="요청납기일" width={280}>
          <CompactDateRange
            from={filter.contract_start_date ?? ""}
            setFrom={(v) => setFilter({ ...filter, contract_start_date: v })}
            to={filter.contract_end_date ?? ""}
            setTo={(v) => setFilter({ ...filter, contract_end_date: v })}
          />
        </CompactFilterField>
      </CompactFilterBar>

      <DataGrid
        columns={columns}
        data={rows}
        loading={loading}
        showRowNumber
        emptyMessage="조건에 맞는 프로젝트가 없습니다."
        gridId="project-progress-wbslist3"
        showColumnSettings
        paginationStyle="range"
        pageSizeOptions={[10, 15, 20, 50, 100]}
        summaryStats={progressSummary}
        onRefresh={fetchList}
        onDownload={() => {
          if (rows.length === 0) { toast.info("내보낼 데이터가 없습니다."); return; }
          const exportRows = rows.map((r) => {
            const out: Record<string, any> = {};
            GRID_COLUMNS.forEach((col) => { out[col.label] = (r as any)[col.key] ?? ""; });
            return out;
          });
          exportToExcel(exportRows, "진행관리.xlsx", "진행관리");
        }}
        showChart
      />

      <ProjectInfoDialog open={infoOpen} onOpenChange={setInfoOpen} data={infoData} />
    </div>
  );
}
