"use client";

// 구매관리 > 구매리스트관리 — wace salesMng/salesRequestMngRegList.jsp 1:1
// 그리드: sales_request_master + mbom_detail/part_mng (품번/품명 1건 + 외 N건) + comm_code 변환
// 검색: 품번 / 품명 / 작성일 / 고객사 / 작성자 / 제품구분 / 프로젝트번호
// 액션: 조회 / 초기화 / [구매리스트 생성→M-BOM 페이지에서 처리] (해당 화면은 조회 전용)

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 { purchaseApi, PurchaseListFilter, OptionItem } from "@/lib/api/purchase";
import { exportToExcel } from "@/lib/utils/excelExport";

const PARENT_PRODUCT = "0000001"; // 제품구분 comm_code parent_code_id

const EMPTY_FILTER: PurchaseListFilter = {
  part_no: "", part_name: "", regdate_start: "", regdate_end: "",
  customer_cd: "", request_user: "", part_type: "", project_no: "",
  page: 1, page_size: 50,
};

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

  const [productOpts, setProductOpts] = useState<SmartSelectOption[]>([]);
  const [userOpts, setUserOpts] = useState<OptionItem[]>([]);

  const fetchList = useCallback(async (override?: Partial<PurchaseListFilter>) => {
    setLoading(true);
    try {
      const f = { ...filter, ...override };
      const res = await purchaseApi.listPurchaseRequest(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 [p, u] = await Promise.all([
          apiClient.get(`/sales/codes/${PARENT_PRODUCT}`),
          purchaseApi.listUsers(),
        ]);
        if (dead) return;
        setProductOpts(p.data?.data ?? []);
        setUserOpts(u);
      } catch { /* skip */ }
    })();
    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}`,
      part_display: r.part_extra_count > 0 ? `${r.part_no} 외 ${r.part_extra_count}건` : r.part_no,
      part_name_display: r.part_extra_count > 0 ? `${r.part_name} 외 ${r.part_extra_count}건` : r.part_name,
    })),
    [rows],
  );

  const GRID_COLUMNS: DataGridColumn[] = useMemo(() => ([
    { key: "request_mng_no",        label: "요청번호",     width: "w-[140px]", align: "center" },
    { key: "purchase_type_name",    label: "구매유형",     width: "w-[115px]", align: "center" },
    { key: "project_number",        label: "프로젝트번호", width: "w-[140px]", align: "center" },
    { key: "order_type_name",       label: "주문유형",     width: "w-[115px]", align: "center" },
    { key: "product_name_full",     label: "제품구분",     width: "w-[115px]", align: "center" },
    { key: "customer_name",         label: "고객사",       minWidth: "min-w-[180px]" },
    { key: "paid_type_name",        label: "유/무상",      width: "w-[100px]", align: "center" },
    { key: "part_display",          label: "품번",         width: "w-[160px]" },
    { key: "part_name_display",     label: "품명",         minWidth: "min-w-[280px]" },
    { key: "has_quotation_request", label: "견적요청서",   width: "w-[115px]", align: "center" },
    { key: "request_user_name",     label: "작성자",       width: "w-[115px]", align: "center" },
    { key: "delivery_request_date", label: "입고요청일",   width: "w-[115px]", align: "center" },
    { key: "regdate_title",         label: "작성일",       width: "w-[115px]", align: "center" },
  ]), []);

  const summary = useMemo(() => {
    const pageCnt = gridRows.length;
    return [
      { label: "전체 건수", value: total.toLocaleString(), suffix: "건" },
      { label: "페이지 건수", value: pageCnt.toLocaleString(), 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()}건</>}>
        <CompactFilterField label="품번" width={150}>
          <Input value={filter.part_no ?? ""}
                 onChange={(e) => setFilter({ ...filter, part_no: e.target.value })} />
        </CompactFilterField>
        <CompactFilterField label="품명" width={150}>
          <Input value={filter.part_name ?? ""}
                 onChange={(e) => setFilter({ ...filter, part_name: e.target.value })} />
        </CompactFilterField>
        <CompactFilterField label="작성일" width={280}>
          <CompactDateRange
            from={filter.regdate_start ?? ""} setFrom={(v) => setFilter({ ...filter, regdate_start: v })}
            to={filter.regdate_end ?? ""}     setTo={(v) => setFilter({ ...filter, regdate_end: v })}
          />
        </CompactFilterField>
        <CompactFilterField label="고객사" width={170}>
          <CustomerSelect value={filter.customer_cd ?? ""}
                          onValueChange={(v) => setFilter({ ...filter, customer_cd: v })} />
        </CompactFilterField>
        <CompactFilterField label="작성자" width={150}>
          <SmartSelect options={userOpts} value={filter.request_user ?? ""}
                       onValueChange={(v) => setFilter({ ...filter, request_user: v })} />
        </CompactFilterField>
        <CompactFilterField label="제품구분" width={130}>
          <SmartSelect options={productOpts} value={filter.part_type ?? ""}
                       onValueChange={(v) => setFilter({ ...filter, part_type: v })} />
        </CompactFilterField>
        <CompactFilterField label="프로젝트번호" width={170}>
          <Input value={filter.project_no ?? ""}
                 onChange={(e) => setFilter({ ...filter, project_no: e.target.value })} />
        </CompactFilterField>
      </CompactFilterBar>

      <DataGrid
        columns={GRID_COLUMNS}
        data={gridRows}
        loading={loading}
        emptyMessage={loading ? "조회 중..." : "데이터가 없습니다"}
        gridId="purchase-list"
        pageSizeOptions={[10, 15, 20, 50, 100]}
        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={["request_user_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
      />
    </div>
  );
}
