"use client";

// 생산관리 > 원자재 소요량 — wace productionplanning/rawMaterialRequirementList.jsp 1:1
// 입력: M-BOM 헤더 선택 + 입력수량 → 여러 행
// 출력: 구매품(PART_TYPE='0000063') + 원소재(RAW_MATERIAL_PART_NO) 합본
// 페이지네이션: 결과 전체. 클라이언트 페이지네이션.

import React, { useCallback, useEffect, useMemo, useState } from "react";
import { Plus, Trash2 } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { toast } from "sonner";
import { DataGrid, DataGridColumn } from "@/components/common/DataGrid";
import { PageHeader } from "@/components/common/PageHeader";
import { mbomRequirementApi, MbomOption, RawRequirementRow } from "@/lib/api/prodPlanResult";
import { exportToExcel } from "@/lib/utils/excelExport";

interface InputRow {
  id: string;
  mbomObjid: string;
  partName: string;
  qty: number;
  checked: boolean;
}

let rowSeq = 0;
const newRow = (): InputRow => ({ id: `r${++rowSeq}`, mbomObjid: "", partName: "", qty: 1, checked: false });

export default function RawMaterialRequirementPage() {
  const [mbomOpts, setMbomOpts] = useState<MbomOption[]>([]);
  const [inputs, setInputs]     = useState<InputRow[]>([newRow()]);
  const [results, setResults]   = useState<RawRequirementRow[]>([]);
  const [loading, setLoading]   = useState(false);

  useEffect(() => {
    (async () => {
      try {
        const opts = await mbomRequirementApi.getOptions();
        setMbomOpts(opts);
      } catch (e: any) {
        toast.error(e?.message ?? "M-BOM 옵션 로드 실패");
      }
    })();
  }, []);

  const partNameMap = useMemo(() => {
    const m = new Map<string, string>();
    mbomOpts.forEach((o) => m.set(o.objid, o.part_name));
    return m;
  }, [mbomOpts]);

  const addRow = () => setInputs((rs) => [...rs, newRow()]);
  const removeChecked = () => {
    const next = inputs.filter((r) => !r.checked);
    if (next.length === inputs.length) {
      toast.info("삭제할 행을 선택해주세요.");
      return;
    }
    setInputs(next.length === 0 ? [newRow()] : next);
  };
  const updateRow = (id: string, patch: Partial<InputRow>) => {
    setInputs((rs) => rs.map((r) => (r.id === id ? { ...r, ...patch } : r)));
  };

  const handleSearch = useCallback(async () => {
    const items = inputs
      .filter((r) => r.mbomObjid && Number(r.qty) > 0)
      .map((r) => ({ mbomObjid: r.mbomObjid, qty: Number(r.qty) }));
    if (items.length === 0) {
      toast.info("M-BOM을 선택하고 수량을 입력해주세요.");
      return;
    }
    setLoading(true);
    try {
      const res = await mbomRequirementApi.getRaw(items);
      setResults(res);
      if (res.length === 0) toast.info("구매품 항목이 없습니다.");
    } catch (e: any) {
      toast.error(e?.response?.data?.message ?? e?.message ?? "조회 실패");
      setResults([]);
    } finally {
      setLoading(false);
    }
  }, [inputs]);

  const resultRows = useMemo(
    () => results.map((r, i) => ({ ...r, id: `${r.PART_NO || r.MATERIAL_PART_NO}__${i}` })),
    [results],
  );

  const RESULT_COLUMNS: DataGridColumn[] = useMemo(() => ([
    { key: "CATEGORY_NAME",         label: "구분",        width: "w-[110px]", align: "center" },
    { key: "PART_NO",               label: "품번",        minWidth: "min-w-[180px]" },
    { key: "PART_NAME",             label: "품명",        minWidth: "min-w-[200px]" },
    { key: "REQUIRED_QTY",          label: "소요량",      width: "w-[110px]", align: "right", formatNumber: true },
    { key: "MATERIAL",              label: "소재",        width: "w-[120px]", align: "center" },
    { key: "SPEC",                  label: "사이즈",      width: "w-[110px]", align: "center" },
    { key: "MATERIAL_PART_NO",      label: "소재품번",    minWidth: "min-w-[180px]" },
    { key: "MATERIAL_REQUIRED_QTY", label: "소재소요량",  width: "w-[110px]", align: "right", formatNumber: true },
  ]), []);

  const summary = useMemo(() => {
    const purchaseCount = resultRows.filter((r: any) => r.CATEGORY_NAME !== "원소재").length;
    const rawCount = resultRows.length - purchaseCount;
    return [
      { label: "조회결과",  value: resultRows.length.toLocaleString(), suffix: "건" },
      { label: "구매품",    value: purchaseCount.toLocaleString(),     suffix: "건" },
      { label: "원소재",    value: rawCount.toLocaleString(),          suffix: "건" },
    ];
  }, [resultRows]);

  return (
    <div className="flex h-full flex-col overflow-hidden p-2 gap-2">
      <PageHeader
        loading={loading}
        onSearch={handleSearch}
        actions={
          <>
            <Button size="sm" variant="outline" className="h-8 gap-1 px-2 text-xs" onClick={addRow}>
              <Plus className="h-3.5 w-3.5" /> 행 추가
            </Button>
            <Button size="sm" variant="outline" className="h-8 gap-1 px-2 text-xs" onClick={removeChecked}>
              <Trash2 className="h-3.5 w-3.5" /> 행 삭제
            </Button>
          </>
        }
      />

      <div className="rounded border bg-white p-2">
        <div className="mb-1 border-l-[3px] border-blue-500 pl-2 text-xs font-semibold">
          M-BOM 선택 및 수량 입력
        </div>
        <div className="overflow-auto" style={{ maxHeight: 180 }}>
          <table className="w-full border-collapse text-xs">
            <thead className="bg-gray-50">
              <tr className="border-b">
                <th className="w-10 border px-1 py-1">선택</th>
                <th className="border px-2 py-1 text-left">M-BOM</th>
                <th className="border px-2 py-1 text-left">품명</th>
                <th className="w-32 border px-2 py-1 text-right">수량</th>
              </tr>
            </thead>
            <tbody>
              {inputs.map((r) => (
                <tr key={r.id} className="border-b">
                  <td className="border px-1 py-1 text-center">
                    <input type="checkbox" checked={r.checked}
                      onChange={(e) => updateRow(r.id, { checked: e.target.checked })} />
                  </td>
                  <td className="border px-1 py-1">
                    <select
                      className="h-7 w-full rounded border px-1 text-xs"
                      value={r.mbomObjid}
                      onChange={(e) => updateRow(r.id, {
                        mbomObjid: e.target.value,
                        partName: partNameMap.get(e.target.value) ?? "",
                      })}
                    >
                      <option value="">선택</option>
                      {mbomOpts.map((o) => (
                        <option key={o.objid} value={o.objid}>{o.mbom_no}</option>
                      ))}
                    </select>
                  </td>
                  <td className="border px-2 py-1 text-gray-700">{r.partName}</td>
                  <td className="border px-1 py-1">
                    <Input
                      type="number" min={1} step={1}
                      className="h-7 text-right text-xs"
                      value={r.qty}
                      onChange={(e) => updateRow(r.id, { qty: Math.max(1, Number(e.target.value) || 1) })}
                    />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <DataGrid
        columns={RESULT_COLUMNS}
        data={resultRows}
        loading={loading}
        showRowNumber
        emptyMessage="조회 결과가 없습니다."
        gridId="production-raw-material-req"
        pageSizeOptions={[25, 50, 100, 200, 500]}
        paginationStyle="range"
        showColumnSettings
        summaryStats={summary}
        onRefresh={handleSearch}
        onDownload={() => {
          if (resultRows.length === 0) { toast.info("내보낼 데이터가 없습니다."); return; }
          const exportRows = resultRows.map((r: any) => {
            const out: Record<string, any> = {};
            RESULT_COLUMNS.forEach((c) => { out[c.label] = r[c.key] ?? ""; });
            return out;
          });
          exportToExcel(exportRows, "원자재_소요량.xlsx", "원자재_소요량");
        }}
        showChart
      />
    </div>
  );
}
