"use client";

// 구매관리 > 발주서관리 — wace_plm purchaseOrder/purchaseOrderList_new.jsp 1:1
// 매퍼: wace_plm/src/com/pms/mapper/purchaseOrder.xml purchaseOrderMasterList_new
// 검색 2행: 년도/고객사/프로젝트번호/발주No/공급업체/품번/품명 +
//          입고요청일/발주일/주문유형/제품구분/구매유형/구매담당자/메일발송
// 그리드 15컬럼: 품의서No/발주서No/프로젝트번호/구매유형/주문유형/제품구분/
//               품번/품명/공급업체/환종/총액/메일발송/발주일/구매담당자/작성일

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 { purchaseApi, PurchaseListFilter, OptionItem, getYearOptions } from "@/lib/api/purchase";
import { apiClient } from "@/lib/api/client";
import { exportToExcel } from "@/lib/utils/excelExport";
import { Button } from "@/components/ui/button";
import { Pencil, Trash2 } from "lucide-react";
import { PurchaseOrderGeneralFormDialog } from "@/components/purchase/PurchaseOrderGeneralFormDialog";
import { PurchaseOrderOutsourcingFormDialog } from "@/components/purchase/PurchaseOrderOutsourcingFormDialog";
import { PurchaseOrderEnglishFormDialog } from "@/components/purchase/PurchaseOrderEnglishFormDialog";
import { PurchaseOrderFormType } from "@/components/purchase/PurchaseOrderFormTypeSelectDialog";
import { useConfirmDialog } from "@/components/common/ConfirmDialog";

const MAIL_SEND_OPTS: SmartSelectOption[] = [
  { code: "Y",           label: "발송완료" },
  { code: "N",           label: "미발송" },
  { code: "orderCancel", label: "발주취소" },
];

const EMPTY_FILTER: PurchaseListFilter = {
  year: String(new Date().getFullYear()),
  customer_cd: "", project_no: "", purchase_order_no: "",
  partner_objid: "", part_no: "", part_name: "",
  delivery_start_date: "", delivery_end_date: "",
  reg_start_date: "", reg_end_date: "",
  category_cd: "", product_cd: "", purchase_type: "", writer: "",
  mail_send_yn: "",
  page: 1, page_size: 50,
};

// wace 코드그룹 ID (PurchaseOrderController.matermgmtList 기준)
const CODE_GROUP = {
  CATEGORY: "0000167",  // 주문유형
  PRODUCT:  "0000001",  // 제품구분
  PURCHASE: "0001814",  // 구매유형
} as const;

async function loadCodes(groupId: string): Promise<OptionItem[]> {
  try {
    const r = await apiClient.get(`/sales/codes/${groupId}`);
    return (r.data?.data ?? []) as OptionItem[];
  } catch {
    return [];
  }
}

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

  const [vendorOpts,   setVendorOpts]   = useState<OptionItem[]>([]);
  const [userOpts,     setUserOpts]     = useState<OptionItem[]>([]);
  const [categoryOpts, setCategoryOpts] = useState<OptionItem[]>([]);
  const [productOpts,  setProductOpts]  = useState<OptionItem[]>([]);
  const [purchaseOpts, setPurchaseOpts] = useState<OptionItem[]>([]);

  // 수정 다이얼로그 — form_type 따라 자동 분기
  const [editObjid, setEditObjid] = useState<string>("");
  const [editFormType, setEditFormType] = useState<PurchaseOrderFormType | "">("");
  const { confirm, ConfirmDialogComponent } = useConfirmDialog();

  const yearOpts = useMemo(() => getYearOptions(), []);

  const fetchList = useCallback(async (override?: Partial<PurchaseListFilter>) => {
    setLoading(true);
    try {
      const f = { ...filter, ...override };
      const res = await purchaseApi.listOrder(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 [v, u, cat, prod, pur] = await Promise.all([
          purchaseApi.listVendors(),
          purchaseApi.listUsers(),
          loadCodes(CODE_GROUP.CATEGORY),
          loadCodes(CODE_GROUP.PRODUCT),
          loadCodes(CODE_GROUP.PURCHASE),
        ]);
        if (dead) return;
        setVendorOpts(v);
        setUserOpts(u);
        setCategoryOpts(cat);
        setProductOpts(prod);
        setPurchaseOpts(pur);
      } 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 ?? `r_${i}` })),
    [rows],
  );

  const GRID_COLUMNS: DataGridColumn[] = useMemo(() => ([
    { key: "proposal_no",        label: "품의서 No",   width: "w-[125px]", align: "center" },
    { key: "purchase_order_no",  label: "발주서 No",   width: "w-[125px]", align: "center" },
    { key: "project_no",         label: "프로젝트번호", width: "w-[140px]", align: "center" },
    { key: "purchase_type_name", label: "구매유형",     width: "w-[110px]", align: "center" },
    { key: "category_name",      label: "주문유형",     width: "w-[110px]", align: "center" },
    { key: "product_name",       label: "제품구분",     width: "w-[110px]", align: "center" },
    { key: "part_no",            label: "품번",         width: "w-[170px]" },
    { key: "part_name",          label: "품명",         minWidth: "min-w-[280px]" },
    { key: "partner_name",       label: "공급업체",     minWidth: "min-w-[170px]" },
    { key: "currency_name",      label: "환종",         width: "w-[80px]",  align: "center" },
    { key: "total_supply_price", label: "총액",         width: "w-[140px]", align: "right", formatMoney: true },
    { key: "mail_send_yn",       label: "메일발송",     width: "w-[100px]", align: "center" },
    { key: "mail_send_date",     label: "발주일",       width: "w-[115px]", align: "center" },
    { key: "writer_name",        label: "구매담당자",   width: "w-[110px]", align: "center" },
    { key: "regdate",            label: "작성일",       width: "w-[115px]", align: "center" },
  ]), []);

  const summary = useMemo(() => [
    { label: "전체 건수", value: total.toLocaleString(), suffix: "건" },
    { label: "선택", value: checkedIds.length.toLocaleString(), suffix: "건" },
  ], [total, checkedIds]);

  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}
        actions={<>
          <Button size="sm" variant="outline" className="h-8 gap-1 px-2 text-xs"
                  disabled={checkedIds.length !== 1}
                  onClick={() => {
                    const id = checkedIds[0]; if (!id) return;
                    const row = rows.find((r: any) => String(r.objid) === id);
                    const ft = (String(row?.form_type || "general") as PurchaseOrderFormType);
                    setEditObjid(id);
                    setEditFormType(ft);
                  }}>
            <Pencil className="h-3.5 w-3.5" /> 수정
          </Button>
          <Button size="sm" variant="destructive" className="h-8 gap-1 px-2 text-xs"
                  disabled={checkedIds.length === 0}
                  onClick={async () => {
                    const ok = await confirm(`선택한 ${checkedIds.length}건을 삭제하시겠어요?`, {
                      description: "발주서와 품목이 함께 삭제돼요.",
                      variant: "destructive",
                      confirmText: "삭제",
                    });
                    if (!ok) return;
                    try {
                      for (const id of checkedIds) {
                        await purchaseApi.deleteOrderForm(id);
                      }
                      toast.success("삭제 완료");
                      setCheckedIds([]);
                      fetchList();
                    } catch (e: any) {
                      toast.error(e?.response?.data?.message ?? e?.message ?? "삭제 실패");
                    }
                  }}>
            <Trash2 className="h-3.5 w-3.5" /> 삭제
          </Button>
        </>} />

      <CompactFilterBar totalText={<>총 {total.toLocaleString()}건</>}>
        <CompactFilterField label="년도" width={100}>
          <SmartSelect options={yearOpts} value={filter.year ?? ""}
                       onValueChange={(v) => setFilter({ ...filter, year: v })} />
        </CompactFilterField>
        <CompactFilterField label="고객사" width={170}>
          <CustomerSelect value={filter.customer_cd ?? ""}
                          onValueChange={(v) => setFilter({ ...filter, customer_cd: v })} />
        </CompactFilterField>
        <CompactFilterField label="프로젝트번호" width={160}>
          <Input value={filter.project_no ?? ""}
                 onChange={(e) => setFilter({ ...filter, project_no: e.target.value })} />
        </CompactFilterField>
        <CompactFilterField label="발주No" width={140}>
          <Input value={filter.purchase_order_no ?? ""}
                 onChange={(e) => setFilter({ ...filter, purchase_order_no: e.target.value })} />
        </CompactFilterField>
        <CompactFilterField label="공급업체" width={180}>
          <SmartSelect options={vendorOpts} value={filter.partner_objid ?? ""}
                       onValueChange={(v) => setFilter({ ...filter, partner_objid: v })} />
        </CompactFilterField>
        <CompactFilterField label="품번" width={140}>
          <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.delivery_start_date ?? ""} setFrom={(v) => setFilter({ ...filter, delivery_start_date: v })}
            to={filter.delivery_end_date ?? ""}     setTo={(v) => setFilter({ ...filter, delivery_end_date: v })}
          />
        </CompactFilterField>
        <CompactFilterField label="발주일" width={280}>
          <CompactDateRange
            from={filter.reg_start_date ?? ""} setFrom={(v) => setFilter({ ...filter, reg_start_date: v })}
            to={filter.reg_end_date ?? ""}     setTo={(v) => setFilter({ ...filter, reg_end_date: v })}
          />
        </CompactFilterField>
        <CompactFilterField label="주문유형" width={130}>
          <SmartSelect options={categoryOpts} value={filter.category_cd ?? ""}
                       onValueChange={(v) => setFilter({ ...filter, category_cd: v })} />
        </CompactFilterField>
        <CompactFilterField label="제품구분" width={130}>
          <SmartSelect options={productOpts} value={filter.product_cd ?? ""}
                       onValueChange={(v) => setFilter({ ...filter, product_cd: v })} />
        </CompactFilterField>
        <CompactFilterField label="구매유형" width={130}>
          <SmartSelect options={purchaseOpts} value={filter.purchase_type ?? ""}
                       onValueChange={(v) => setFilter({ ...filter, purchase_type: v })} />
        </CompactFilterField>
        <CompactFilterField label="구매담당자" width={150}>
          <SmartSelect options={userOpts} value={filter.writer ?? ""}
                       onValueChange={(v) => setFilter({ ...filter, writer: v })} />
        </CompactFilterField>
        <CompactFilterField label="메일발송" width={130}>
          <SmartSelect options={MAIL_SEND_OPTS} value={filter.mail_send_yn ?? ""}
                       onValueChange={(v) => setFilter({ ...filter, mail_send_yn: v })} />
        </CompactFilterField>
      </CompactFilterBar>

      <DataGrid
        columns={GRID_COLUMNS}
        data={gridRows}
        loading={loading}
        showCheckbox
        checkedIds={checkedIds}
        onCheckedChange={setCheckedIds}
        emptyMessage={loading ? "조회 중..." : "데이터가 없습니다"}
        gridId="purchase-order"
        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}
        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
        onRowClick={(row: any) => {
          if (!row?.objid) return;
          setEditObjid(String(row.objid));
          setEditFormType(String(row.form_type || "general") as PurchaseOrderFormType);
        }}
      />

      <PurchaseOrderGeneralFormDialog
        open={editFormType === "general"}
        pomObjid={editObjid}
        onClose={() => setEditFormType("")}
        onSaved={() => { setEditFormType(""); fetchList(); }}
      />
      <PurchaseOrderOutsourcingFormDialog
        open={editFormType === "outsourcing"}
        pomObjid={editObjid}
        onClose={() => setEditFormType("")}
        onSaved={() => { setEditFormType(""); fetchList(); }}
      />
      <PurchaseOrderEnglishFormDialog
        open={editFormType === "english"}
        pomObjid={editObjid}
        onClose={() => setEditFormType("")}
        onSaved={() => { setEditFormType(""); fetchList(); }}
      />

      {ConfirmDialogComponent}
    </div>
  );
}
