"use client";

// 생산관리 > 생산계획&실적관리(장비) — wace productionplanning/prodPlanResultMgmtEquipList.jsp 1:1
// PROJECT_MGMT WHERE CM.PRODUCT='0000928'. PMS_WBS_TASK 기반 생산/납품 진척율.
// 페이지네이션: 서버사이드.
// (WBS 할당 모달은 wace_plm 의 별 작업이라 본 페이지에서는 제외 — 본 PR-D2 범위 외)

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 { SmartSelect, SmartSelectOption } from "@/components/common/SmartSelect";
import { CustomerSelect } from "@/components/common/CustomerSelect";
import { CompactFilterBar, CompactFilterField, CompactDateRange } from "@/components/common/CompactFilterBar";
import { PageHeader } from "@/components/common/PageHeader";
import { apiClient } from "@/lib/api/client";
import { prodPlanResultApi, ProdPlanResultFilter, ProdPlanResultEquipRow } from "@/lib/api/prodPlanResult";
import { exportToExcel } from "@/lib/utils/excelExport";

const PARENT_PRODUCT       = "0000001";
const PARENT_CATEGORY      = "0000167";
const PARENT_PRODUCTION_TY = "0001832";

interface CodeOpt extends SmartSelectOption { sort?: number | null }

const EMPTY_FILTER: ProdPlanResultFilter = {
  search_project_nos: "",
  search_product_code: "",
  search_category_code: "",
  search_production_type: "",
  search_customer_objid: "",
  search_req_del_date_from: "",
  search_req_del_date_to: "",
  search_part_no: "",
  search_part_name: "",
  search_serial_no: "",
  page: 1,
  page_size: 50,
};

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

  const [categoryOpts, setCategoryOpts]   = useState<CodeOpt[]>([]);
  const [productOpts,  setProductOpts]    = useState<CodeOpt[]>([]);
  const [prodTypeOpts, setProdTypeOpts]   = useState<CodeOpt[]>([]);
  const [projectOpts,  setProjectOpts]    = useState<SmartSelectOption[]>([]);

  const fetchList = useCallback(async (override?: Partial<ProdPlanResultFilter>) => {
    setLoading(true);
    try {
      const f = { ...filter, ...override };
      const res = await prodPlanResultApi.listEquip(f);
      setRows(res.rows ?? []);
      setTotal(res.totalCount ?? 0);
    } catch (e: any) {
      toast.error(e?.response?.data?.message ?? e?.message ?? "조회 실패");
    } finally {
      setLoading(false);
    }
  }, [filter]);

  useEffect(() => {
    let dead = false;
    (async () => {
      try {
        const [c1, c2, c3, proj] = await Promise.all([
          apiClient.get(`/sales/codes/${PARENT_CATEGORY}`),
          apiClient.get(`/sales/codes/${PARENT_PRODUCT}`),
          apiClient.get(`/sales/codes/${PARENT_PRODUCTION_TY}`),
          prodPlanResultApi.getProjectOptions(),
        ]);
        if (dead) return;
        setCategoryOpts(c1.data?.data ?? []);
        setProductOpts(c2.data?.data ?? []);
        setProdTypeOpts(c3.data?.data ?? []);
        setProjectOpts(proj);
      } catch {/* ignore */}
    })();
    fetchList(EMPTY_FILTER);
    return () => { dead = true; };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const gridRows = useMemo(
    () => rows.map((r, i) => ({ ...r, id: `${r.objid}__${i}` })),
    [rows],
  );

  const GRID_COLUMNS: DataGridColumn[] = useMemo(() => ([
    { key: "project_no",           label: "프로젝트번호",   width: "w-[140px]" },
    { key: "product_name",         label: "제품구분",       width: "w-[110px]", align: "center" },
    { key: "category_code_name",   label: "주문유형",       width: "w-[110px]", align: "center" },
    { key: "production_type_name", label: "생산유형",       width: "w-[110px]", align: "center" },
    { key: "customer_name",        label: "고객사",         minWidth: "min-w-[160px]" },
    { key: "req_del_date",         label: "요청납기",       width: "w-[115px]", align: "center" },
    { key: "customer_request",     label: "고객사요청사항", minWidth: "min-w-[200px]" },
    { key: "part_no",              label: "품번",           width: "w-[140px]" },
    { key: "part_name",            label: "품명",           minWidth: "min-w-[180px]" },
    { key: "serial_no",            label: "S/N",            width: "w-[110px]", align: "center" },
    { key: "prod_wbs_cnt",         label: "생산WBS",        width: "w-[110px]", align: "right", formatNumber: true },
    { key: "prod_progress_rate",   label: "생산진척율(%)",  width: "w-[140px]", align: "right" },
    { key: "delv_wbs_cnt",         label: "납품WBS",        width: "w-[110px]", align: "right", formatNumber: true },
    { key: "delv_progress_rate",   label: "납품진척율(%)",  width: "w-[140px]", align: "right" },
  ]), []);

  const summary = useMemo(() => {
    const pageCount = gridRows.length;
    const avg = (key: string) => {
      if (pageCount === 0) return 0;
      const sum = gridRows.reduce((a, r: any) => a + Number(r[key] || 0), 0);
      return sum / pageCount;
    };
    const intFmt = (n: number) => n.toLocaleString();
    return [
      { label: "전체 건수",      value: intFmt(total),     suffix: "건" },
      { label: "페이지 건수",    value: intFmt(pageCount), suffix: "건" },
      { label: "생산진척율 평균", value: avg("prod_progress_rate").toFixed(1), suffix: "%" },
      { label: "납품진척율 평균", value: avg("delv_progress_rate").toFixed(1), suffix: "%" },
    ];
  }, [gridRows, total]);

  const handleSearch = () => { setFilter((f) => ({ ...f, page: 1 })); fetchList({ page: 1 }); };
  const handleReset  = () => { setFilter(EMPTY_FILTER); fetchList(EMPTY_FILTER); };

  return (
    <div className="flex h-full flex-col overflow-hidden p-2 gap-2">
      <PageHeader loading={loading} onSearch={handleSearch} onReset={handleReset} />
      <CompactFilterBar totalText={<>총 {total.toLocaleString()}건 · PRODUCT=장비(0000928) 만</>}>
        <CompactFilterField label="프로젝트번호" width={180}>
          <SmartSelect options={projectOpts} value={filter.search_project_nos ?? ""}
            onValueChange={(v) => setFilter({ ...filter, search_project_nos: v })} />
        </CompactFilterField>
        <CompactFilterField label="제품구분" width={130}>
          <SmartSelect options={productOpts} value={filter.search_product_code ?? ""}
            onValueChange={(v) => setFilter({ ...filter, search_product_code: v })} />
        </CompactFilterField>
        <CompactFilterField label="주문유형" width={130}>
          <SmartSelect options={categoryOpts} value={filter.search_category_code ?? ""}
            onValueChange={(v) => setFilter({ ...filter, search_category_code: v })} />
        </CompactFilterField>
        <CompactFilterField label="생산유형" width={130}>
          <SmartSelect options={prodTypeOpts} value={filter.search_production_type ?? ""}
            onValueChange={(v) => setFilter({ ...filter, search_production_type: v })} />
        </CompactFilterField>
        <CompactFilterField label="고객사" width={170}>
          <CustomerSelect value={filter.search_customer_objid ?? ""}
            onValueChange={(v) => setFilter({ ...filter, search_customer_objid: v })} />
        </CompactFilterField>
        <CompactFilterField label="요청납기" width={280}>
          <CompactDateRange
            from={filter.search_req_del_date_from ?? ""} setFrom={(v) => setFilter({ ...filter, search_req_del_date_from: v })}
            to={filter.search_req_del_date_to ?? ""}     setTo={(v) => setFilter({ ...filter, search_req_del_date_to: v })} />
        </CompactFilterField>
        <CompactFilterField label="품번" width={130}>
          <Input value={filter.search_part_no ?? ""} onChange={(e) => setFilter({ ...filter, search_part_no: e.target.value })} />
        </CompactFilterField>
        <CompactFilterField label="품명" width={150}>
          <Input value={filter.search_part_name ?? ""} onChange={(e) => setFilter({ ...filter, search_part_name: e.target.value })} />
        </CompactFilterField>
        <CompactFilterField label="S/N" width={130}>
          <Input value={filter.search_serial_no ?? ""} onChange={(e) => setFilter({ ...filter, search_serial_no: e.target.value })} />
        </CompactFilterField>
      </CompactFilterBar>

      <DataGrid
        columns={GRID_COLUMNS}
        data={gridRows}
        loading={loading}
        showRowNumber
        showCheckbox
        emptyMessage="조건에 맞는 데이터가 없습니다."
        gridId="production-plan-result-equip"
        pageSizeOptions={[25, 50, 100, 200, 500]}
        paginationStyle="range"
        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 }); }}
        showColumnSettings
        summaryStats={summary}
        onRefresh={() => fetchList()}
        onDownload={() => {
          if (gridRows.length === 0) { toast.info("내보낼 데이터가 없습니다."); return; }
          const exportRows = gridRows.map((r: any) => {
            const out: Record<string, any> = {};
            GRID_COLUMNS.forEach((c) => { out[c.label] = r[c.key] ?? ""; });
            return out;
          });
          exportToExcel(exportRows, "생산계획_실적관리_장비.xlsx", "생산계획_실적관리_장비");
        }}
        showChart
      />
    </div>
  );
}
