"use client";

// 생산관리 > 생산계획&실적관리 — wace productionplanning/prodPlanResultMgmtList.jsp 1:1
// 그리드: PROJECT_MGMT × CONTRACT_ITEM × PRODUCTION_PLAN × PRODUCTION_RESULT 합산 + 독립 PP 합본
// 필터: 프로젝트번호 / 제품구분 / 주문유형 / 생산유형 / 고객사 / 요청납기 / 품번 / 품명 / S/N / 등록자 / 등록일
// 페이지네이션: 서버사이드 (page / page_size / totalCount)

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, ProdPlanResultRow } 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: "",
  search_writer: "",
  search_regdate_from: "",
  search_regdate_to: "",
  page: 1,
  page_size: 50,
};

export default function ProdPlanResultPage() {
  const [rows, setRows]   = useState<ProdPlanResultRow[]>([]);
  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 [writerOpts,   setWriterOpts]     = useState<SmartSelectOption[]>([]);

  const [serialOpen, setSerialOpen] = useState(false);
  const [serialList, setSerialList] = useState<string[]>([]);

  const fetchList = useCallback(async (override?: Partial<ProdPlanResultFilter>) => {
    setLoading(true);
    try {
      const f = { ...filter, ...override };
      const res = await prodPlanResultApi.list(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, writers] = await Promise.all([
          apiClient.get(`/sales/codes/${PARENT_CATEGORY}`),
          apiClient.get(`/sales/codes/${PARENT_PRODUCT}`),
          apiClient.get(`/sales/codes/${PARENT_PRODUCTION_TY}`),
          prodPlanResultApi.getProjectOptions(),
          prodPlanResultApi.getWriterOptions(),
        ]);
        if (dead) return;
        setCategoryOpts(c1.data?.data ?? []);
        setProductOpts(c2.data?.data ?? []);
        setProdTypeOpts(c3.data?.data ?? []);
        setProjectOpts(proj);
        setWriterOpts(writers);
      } 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 openSerial = useCallback((row: any) => {
    const list = String(row?.serial_no_list ?? "")
      .split(",").map((s) => s.trim()).filter(Boolean);
    if (list.length === 0) { toast.info("S/N 정보가 없습니다."); return; }
    setSerialList(list);
    setSerialOpen(true);
  }, []);

  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-[190px]" },
    { 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", onClick: openSerial },
    { key: "quantity",            label: "수주수량",       width: "w-[110px]", align: "right", formatNumber: true },
    { key: "extra_prod_qty",      label: "추가생산수량",   width: "w-[130px]", align: "right", formatNumber: true },
    { key: "total_prod_qty",      label: "총생산수량",     width: "w-[120px]", align: "right", formatNumber: true },
    { key: "assembly_qty",        label: "완조립",         width: "w-[95px]",  align: "right", formatNumber: true },
    { key: "inspection_qty",      label: "검사",           width: "w-[85px]",  align: "right", formatNumber: true },
    { key: "ship_wait_qty",       label: "포장",           width: "w-[85px]",  align: "right", formatNumber: true },
    { key: "writer_name",         label: "등록자",         width: "w-[95px]",  align: "center" },
    { key: "regdate_title",       label: "등록일",         width: "w-[105px]", align: "center" },
  ]), [openSerial]);

  const summary = useMemo(() => {
    const pageCount = gridRows.length;
    const qtySum   = gridRows.reduce((a, r: any) => a + Number(r.quantity || 0), 0);
    const totalSum = gridRows.reduce((a, r: any) => a + Number(r.total_prod_qty || 0), 0);
    const asmSum   = gridRows.reduce((a, r: any) => a + Number(r.assembly_qty || 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(totalSum) },
      { label: "완조립 합",   value: intFmt(asmSum) },
    ];
  }, [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()}건 · 프로젝트+독립계획 합본</>}>
        <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>
        <CompactFilterField label="등록자" width={130}>
          <SmartSelect options={writerOpts} value={filter.search_writer ?? ""}
            onValueChange={(v) => setFilter({ ...filter, search_writer: v })} />
        </CompactFilterField>
        <CompactFilterField label="등록일" width={280}>
          <CompactDateRange
            from={filter.search_regdate_from ?? ""} setFrom={(v) => setFilter({ ...filter, search_regdate_from: v })}
            to={filter.search_regdate_to ?? ""}     setTo={(v) => setFilter({ ...filter, search_regdate_to: v })} />
        </CompactFilterField>
      </CompactFilterBar>

      <DataGrid
        columns={GRID_COLUMNS}
        data={gridRows}
        loading={loading}
        showRowNumber
        showCheckbox
        emptyMessage="조건에 맞는 데이터가 없습니다."
        gridId="production-plan-result"
        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}
        systemColumnKeys={["writer_name", "regdate_title"]}
        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
      />

      {serialOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40"
             onClick={() => setSerialOpen(false)}>
          <div className="w-[500px] max-h-[70vh] overflow-auto rounded bg-white p-4 shadow"
               onClick={(e) => e.stopPropagation()}>
            <div className="mb-2 text-sm font-semibold">S/N 목록 ({serialList.length}건)</div>
            <ol className="list-decimal pl-6 text-sm">
              {serialList.map((sn, i) => <li key={i} className="py-0.5">{sn}</li>)}
            </ol>
            <div className="mt-3 text-right">
              <button className="rounded bg-blue-600 px-3 py-1 text-xs text-white"
                      onClick={() => setSerialOpen(false)}>확인</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
