"use client";

// 구매관리 > 입고관리 — wace purchaseOrder/deliveryMngAcceptanceList.jsp 1:1
// 검색: 년도/고객사/프로젝트번호/발주No/규격/품명/공급업체/구매담당자/입고요청일/발주일/입고결과/품번
// 그리드: 18컬럼 (품의서/발주서No, 프로젝트, 품번/품명/공급업체, 환종, 담당자, 입고등록자/일,
//           발주/입고/미입고 수량+금액, 업체성적서, 입고결과)
// 액션: 조회 / 입고등록
// ⚠️ 백엔드 purchase_order_part / arrival_plan 미존재 → 빈 그리드 (UI 만 제공)

import React, { useCallback, useEffect, useMemo, useState } from "react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { PackagePlus } from "lucide-react";
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 { exportToExcel } from "@/lib/utils/excelExport";
import { InboundFormDialog } from "@/components/purchase/InboundFormDialog";

const DELIVERY_STATUS_OPTS: SmartSelectOption[] = [
  { code: "입고중",  label: "입고중" },
  { code: "입고완료", label: "입고완료" },
  { code: "지연",   label: "지연" },
];

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

export default function InboundPage() {
  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 [supplierOpts, setSupplierOpts] = useState<OptionItem[]>([]);
  const [userOpts, setUserOpts] = useState<OptionItem[]>([]);

  // 입고등록 다이얼로그
  const [inboundOpen, setInboundOpen] = useState(false);
  const [inboundPomObjid, setInboundPomObjid] = useState("");

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

  const fetchList = useCallback(async (override?: Partial<PurchaseListFilter>) => {
    setLoading(true);
    try {
      const f = { ...filter, ...override };
      const res = await purchaseApi.listInbound(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 [s, u] = await Promise.all([
          purchaseApi.listSuppliers(),
          purchaseApi.listUsers(),
        ]);
        if (dead) return;
        setSupplierOpts(s);
        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_${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-[135px]", align: "center" },
    { key: "part_no",                  label: "품번",         width: "w-[140px]" },
    { key: "part_name",                label: "품명",         width: "w-[280px]" },
    { key: "partner_name",             label: "공급업체",     minWidth: "min-w-[150px]" },
    { key: "currency_name",            label: "환종",         width: "w-[80px]",  align: "center" },
    { key: "writer_name",              label: "구매담당자",   width: "w-[110px]", align: "center" },
    { key: "delivery_writer_name",     label: "입고등록자",   width: "w-[110px]", align: "center" },
    { key: "delivery_regdate",         label: "입고등록일",   width: "w-[115px]", align: "center" },
    { key: "total_po_qty",             label: "발주수량",     width: "w-[110px]", align: "right", formatNumber: true },
    { key: "total_delivery_qty",       label: "입고수량",     width: "w-[110px]", align: "right", formatNumber: true },
    { key: "non_delivery_qty",         label: "미입고수량",   width: "w-[110px]", align: "right", formatNumber: true },
    { key: "total_supply_price",       label: "발주금액",     width: "w-[120px]", align: "right", formatMoney: true },
    { key: "total_delivery_price",     label: "입고금액",     width: "w-[120px]", align: "right", formatMoney: true },
    { key: "total_not_delivery_price", label: "미입고금액",   width: "w-[120px]", align: "right", formatMoney: true },
    { key: "inspection_file_cnt",      label: "업체성적서",   width: "w-[110px]", align: "center", renderType: "clip" },
    { key: "delivery_status",          label: "입고결과",     width: "w-[110px]", 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="default" 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 pomObjid = String(row?.objid ?? id);
                    setInboundPomObjid(pomObjid);
                    setInboundOpen(true);
                  }}>
            <PackagePlus 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={130}>
          <Input value={filter.part_spec ?? ""}
                 onChange={(e) => setFilter({ ...filter, part_spec: 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={170}>
          <SmartSelect options={supplierOpts} value={filter.partner_objid ?? ""}
                       onValueChange={(v) => setFilter({ ...filter, partner_objid: v })} />
        </CompactFilterField>
        <CompactFilterField label="구매담당자" width={150}>
          <SmartSelect options={userOpts} value={filter.sales_mng_user_id ?? ""}
                       onValueChange={(v) => setFilter({ ...filter, sales_mng_user_id: v })} />
        </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={120}>
          <SmartSelect options={DELIVERY_STATUS_OPTS} value={filter.delivery_status ?? ""}
                       onValueChange={(v) => setFilter({ ...filter, delivery_status: v })} />
        </CompactFilterField>
        <CompactFilterField label="품번" width={140}>
          <Input value={filter.part_no ?? ""}
                 onChange={(e) => setFilter({ ...filter, part_no: e.target.value })} />
        </CompactFilterField>
      </CompactFilterBar>

      <DataGrid
        columns={GRID_COLUMNS}
        data={gridRows}
        loading={loading}
        showCheckbox
        checkedIds={checkedIds}
        onCheckedChange={setCheckedIds}
        emptyMessage={loading ? "조회 중..." : "데이터가 없습니다"}
        gridId="purchase-inbound"
        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={["delivery_writer_name", "delivery_regdate"]}
        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
      />

      <InboundFormDialog
        open={inboundOpen}
        pomObjid={inboundPomObjid}
        onClose={() => setInboundOpen(false)}
        onSaved={() => { setInboundOpen(false); fetchList(); }}
      />
    </div>
  );
}
