"use client";

// 자재관리 > 자재리스트 — wace inventoryMng/inventoryMngNewList.jsp 1:1
// 그리드: inventory_mgmt + part_mng + 입출고 집계 (USE_CNT / USE_CNT_ALL / REQUEST_QTY)
// 검색: 프로젝트 / 유닛 / 품번 / 품명 / PART구분 / Location
// 액션: 재고등록 / 자재이동 / 불출의뢰 / 삭제 / 이력보기

import React, { useCallback, useEffect, useMemo, useState } from "react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Plus, Repeat, ClipboardEdit, Trash2, History as HistoryIcon } from "lucide-react";
import { toast } from "sonner";
import { DataGrid, DataGridColumn } from "@/components/common/DataGrid";
import { SmartSelect } from "@/components/common/SmartSelect";
import { CompactFilterBar, CompactFilterField } from "@/components/common/CompactFilterBar";
import { PageHeader } from "@/components/common/PageHeader";
import { exportToExcel } from "@/lib/utils/excelExport";
import { inventoryMngApi, InventoryListFilter, OptionItem } from "@/lib/api/inventoryMng";
import { StockRegisterDialog } from "@/components/material/StockRegisterDialog";
import { MaterialMoveDialog } from "@/components/material/MaterialMoveDialog";
import { IssueRequestCreateDialog } from "@/components/material/IssueRequestCreateDialog";
import { InventoryHistoryDialog } from "@/components/material/InventoryHistoryDialog";

const EMPTY: InventoryListFilter = {
  project_objid: "", unit_code: "",
  part_no: "", part_name: "",
  part_type: "", location: "",
  page: 1, page_size: 50,
};

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

  const [projectOpts, setProjectOpts] = useState<OptionItem[]>([]);
  const [unitOpts, setUnitOpts] = useState<OptionItem[]>([]);

  const [stockOpen, setStockOpen] = useState(false);
  const [moveOpen, setMoveOpen] = useState(false);
  const [issueOpen, setIssueOpen] = useState(false);
  const [historyOpen, setHistoryOpen] = useState(false);
  const [historyTarget, setHistoryTarget] = useState<{ objid: string; label: string } | null>(null);

  const fetchList = useCallback(async (override?: Partial<InventoryListFilter>) => {
    setLoading(true);
    try {
      const f = { ...filter, ...override };
      const res = await inventoryMngApi.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(() => {
    (async () => {
      try { setProjectOpts(await inventoryMngApi.projects()); } catch { /* skip */ }
    })();
    fetchList(EMPTY);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (!filter.project_objid) { setUnitOpts([]); return; }
    (async () => {
      try { setUnitOpts(await inventoryMngApi.units(filter.project_objid!)); } catch { /* skip */ }
    })();
  }, [filter.project_objid]);

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

  const checkedObjids = useMemo(
    () => gridRows.filter((r: any) => checkedIds.includes(r.id)).map((r: any) => r.objid as string),
    [checkedIds, gridRows],
  );

  const checkedRows = useMemo(
    () => gridRows.filter((r: any) => checkedIds.includes(r.id)),
    [checkedIds, gridRows],
  );

  const GRID_COLUMNS: DataGridColumn[] = useMemo(() => ([
    { key: "project_no",     label: "프로젝트번호", width: "w-[120px]", align: "center" },
    { key: "unit_name",      label: "유닛명",       width: "w-[150px]" },
    { key: "part_no",        label: "품번",         width: "w-[160px]" },
    { key: "part_name",      label: "품명",         minWidth: "min-w-[200px]" },
    { key: "material",       label: "재질",         width: "w-[110px]" },
    { key: "spec",           label: "사양(규격)",   minWidth: "min-w-[140px]" },
    { key: "part_type_name", label: "PART구분",     width: "w-[100px]", align: "center" },
    { key: "use_cnt",        label: "보유수량",     width: "w-[100px]", align: "right",
      render: (v: any) => Number(v ?? 0).toLocaleString() },
    { key: "use_cnt_all",    label: "보유수량(전체)", width: "w-[110px]", align: "right",
      render: (v: any) => Number(v ?? 0).toLocaleString() },
    { key: "location_name",  label: "Location",     width: "w-[140px]" },
    { key: "request_qty",    label: "불출이력",     width: "w-[100px]", align: "right",
      render: (v: any) => Number(v ?? 0).toLocaleString() },
  ]), []);

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

  const handleSearch = () => { setFilter(f => ({ ...f, page: 1 })); fetchList({ page: 1 }); };
  const handleReset  = () => { setFilter(EMPTY); setCheckedIds([]); fetchList(EMPTY); };

  const handleDelete = async () => {
    if (!checkedObjids.length) return toast.info("삭제할 자재를 선택해주세요.");
    if (!confirm(`선택한 ${checkedObjids.length}건의 자재를 삭제하시겠습니까?`)) return;
    try {
      await inventoryMngApi.deleteStock(checkedObjids);
      toast.success("삭제되었습니다.");
      setCheckedIds([]);
      fetchList();
    } catch (e: any) {
      toast.error(e?.response?.data?.message ?? e?.message ?? "삭제 실패");
    }
  };

  const handleMove = () => {
    if (!checkedRows.length) return toast.info("이동할 자재를 선택해주세요.");
    if (checkedRows.some((r: any) => Number(r.use_cnt) === 0)) {
      return toast.warning("보유수량이 0인 자재가 포함되어 있습니다.");
    }
    setMoveOpen(true);
  };

  const handleIssue = () => {
    if (!checkedRows.length) return toast.info("불출의뢰할 자재를 선택해주세요.");
    if (checkedRows.some((r: any) => Number(r.use_cnt) === 0)) {
      return toast.warning("보유수량이 0인 자재가 포함되어 있습니다.");
    }
    setIssueOpen(true);
  };

  const handleHistoryOne = () => {
    if (checkedRows.length !== 1) return toast.info("이력은 1건씩 조회합니다.");
    const r = checkedRows[0] as any;
    setHistoryTarget({ objid: r.objid, label: `${r.part_no} ${r.part_name ?? ""}` });
    setHistoryOpen(true);
  };

  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"
                  onClick={() => setStockOpen(true)}>
            <Plus className="h-3.5 w-3.5" /> 재고등록
          </Button>
          <Button size="sm" variant="outline" className="h-8 gap-1 px-2 text-xs"
                  onClick={handleMove} disabled={!checkedRows.length}>
            <Repeat className="h-3.5 w-3.5" /> 자재이동
          </Button>
          <Button size="sm" variant="outline" className="h-8 gap-1 px-2 text-xs"
                  onClick={handleIssue} disabled={!checkedRows.length}>
            <ClipboardEdit className="h-3.5 w-3.5" /> 불출의뢰
          </Button>
          <Button size="sm" variant="ghost" className="h-8 gap-1 px-2 text-xs"
                  onClick={handleHistoryOne} disabled={checkedRows.length !== 1}>
            <HistoryIcon className="h-3.5 w-3.5" /> 이력
          </Button>
          <Button size="sm" variant="ghost" className="h-8 gap-1 px-2 text-xs text-red-600"
                  onClick={handleDelete} disabled={!checkedRows.length}>
            <Trash2 className="h-3.5 w-3.5" /> 삭제
          </Button>
        </>}
      />

      <CompactFilterBar totalText={<>총 {total.toLocaleString()}건</>}>
        <CompactFilterField label="프로젝트" width={200}>
          <SmartSelect options={projectOpts} value={filter.project_objid ?? ""}
            onValueChange={(v) => setFilter({ ...filter, project_objid: v, unit_code: "" })} />
        </CompactFilterField>
        <CompactFilterField label="유닛" width={180}>
          <SmartSelect options={unitOpts} value={filter.unit_code ?? ""}
            onValueChange={(v) => setFilter({ ...filter, unit_code: v })} />
        </CompactFilterField>
        <CompactFilterField label="품번" width={160}>
          <Input value={filter.part_no ?? ""}
            onChange={(e) => setFilter({ ...filter, part_no: e.target.value })} />
        </CompactFilterField>
        <CompactFilterField label="품명" width={170}>
          <Input value={filter.part_name ?? ""}
            onChange={(e) => setFilter({ ...filter, part_name: e.target.value })} />
        </CompactFilterField>
        <CompactFilterField label="PART구분" width={120}>
          <Input value={filter.part_type ?? ""}
            onChange={(e) => setFilter({ ...filter, part_type: e.target.value })} />
        </CompactFilterField>
        <CompactFilterField label="Location" width={150}>
          <Input value={filter.location ?? ""}
            onChange={(e) => setFilter({ ...filter, location: e.target.value })} />
        </CompactFilterField>
      </CompactFilterBar>

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

      <StockRegisterDialog open={stockOpen} onClose={() => setStockOpen(false)}
        onSaved={() => fetchList()} />

      <MaterialMoveDialog open={moveOpen} onClose={() => setMoveOpen(false)}
        onSaved={() => { setCheckedIds([]); fetchList(); }}
        selectedRows={checkedRows} />

      <IssueRequestCreateDialog open={issueOpen} onClose={() => setIssueOpen(false)}
        onSaved={() => { setCheckedIds([]); fetchList(); }}
        parentObjids={checkedObjids} />

      {historyTarget && (
        <InventoryHistoryDialog open={historyOpen} onClose={() => setHistoryOpen(false)}
          parentObjid={historyTarget.objid} partLabel={historyTarget.label} />
      )}
    </div>
  );
}
