"use client";

/**
 * 수입검사 요청 — wace_plm 의 incomingInspectionList.jsp 1:1 이식.
 * 필터 12종, 그리드 12컬럼.
 */
import React, { useCallback, useEffect, useState } from "react";
import { Plus } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { toast } from "sonner";
import { useAuth } from "@/hooks/useAuth";
import { DataGrid, DataGridColumn } from "@/components/common/DataGrid";
import { PageHeader } from "@/components/common/PageHeader";
import { CompactFilterBar, CompactFilterField, CompactDateRange } from "@/components/common/CompactFilterBar";
import { qualityApi, IncomingRequestRow } from "@/lib/api/quality";
import { exportToExcel } from "@/lib/utils/excelExport";

// wace_plm incomingInspectionList.jsp 그리드 1:1 (12 컬럼)
const GRID_COLUMNS: DataGridColumn[] = [
  { key: "proposal_no",       label: "품의서 No",   width: "w-[130px]", align: "center", frozen: true },
  { key: "purchase_order_no", label: "발주서 No",   width: "w-[130px]", align: "center" },
  { key: "project_no",        label: "프로젝트번호", width: "w-[140px]", align: "center" },
  { key: "product_name",      label: "제품구분",    width: "w-[110px]", align: "center" },
  { key: "part_no",           label: "품번",        width: "w-[140px]" },
  { key: "part_name",         label: "품명",        width: "w-[180px]" },
  { key: "partner_name",      label: "공급업체",    width: "w-[160px]" },
  { key: "delivery_status",   label: "입고결과",    width: "w-[100px]", align: "center" },
  { key: "request_date",      label: "요청일",      width: "w-[115px]", align: "center" },
  { key: "request_user_name", label: "요청자",      width: "w-[100px]", align: "center" },
  { key: "inspection_yn",     label: "검사여부",    width: "w-[100px]", align: "center" },
  { key: "request_status",    label: "요청현황",    width: "w-[110px]", align: "center" },
];

// 하드코딩 옵션 (wace_plm 동일)
const DELIVERY_STATUS_OPTIONS = ["전체", "입고중", "입고완료", "지연"];
const INSPECTION_YN_OPTIONS   = ["전체", "검사", "스킵"];
const REQUEST_STATUS_OPTIONS  = ["전체", "미요청", "요청중", "요청완료"];

export default function IncomingRequestPage() {
  const { user } = useAuth();
  const [rows, setRows] = useState<IncomingRequestRow[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedId, setSelectedId] = useState<string | null>(null);

  const [search, setSearch] = useState({
    search_proposal_no: "",
    search_purchase_order_no: "",
    project_no: "",
    search_part_no: "",
    search_part_name: "",
    search_partner: "",
    search_delivery_status: "",
    search_product_cd: "",
    search_inspection_yn: "",
    search_request_status: "",
    request_user_id: "",
    request_start_date: "",
    request_end_date: "",
  });

  const fetchList = useCallback(async () => {
    if (!user) return;
    setLoading(true);
    try {
      const res = await qualityApi.incomingRequest(search);
      setRows(res.list.map((r) => ({ ...r, id: r.objid } as any)));
      setSelectedId(null);
    } catch {
      toast.error("수입검사 요청 목록 조회 실패");
    } finally { setLoading(false); }
  }, [user, search]);

  useEffect(() => { fetchList(); }, [fetchList]);

  const handleReset = () => setSearch({
    search_proposal_no: "", search_purchase_order_no: "", project_no: "",
    search_part_no: "", search_part_name: "", search_partner: "",
    search_delivery_status: "", search_product_cd: "",
    search_inspection_yn: "", search_request_status: "",
    request_user_id: "", request_start_date: "", request_end_date: "",
  });

  const HardcodedSelect = ({ value, onChange, options }: { value: string; onChange: (v: string) => void; options: string[] }) => (
    <Select value={value || "all"} onValueChange={(v) => onChange(v === "all" || v === "전체" ? "" : v)}>
      <SelectTrigger className="h-7 text-xs"><SelectValue placeholder="전체" /></SelectTrigger>
      <SelectContent>
        {options.map((o) => <SelectItem key={o} value={o === "전체" ? "all" : o}>{o}</SelectItem>)}
      </SelectContent>
    </Select>
  );

  return (
    <div className="flex h-full flex-col overflow-hidden p-2 gap-2">
      <PageHeader
        loading={loading}
        onSearch={fetchList}
        onReset={handleReset}
        actions={
          <Button size="sm" className="h-8 gap-1 text-xs" disabled>
            <Plus className="h-3.5 w-3.5" />수입검사 요청
          </Button>
        }
      />
      <CompactFilterBar totalText={<>총 {rows.length.toLocaleString()}건</>}>
        <CompactFilterField label="품의서 No" width={130}>
          <Input value={search.search_proposal_no} onChange={(e) => setSearch({ ...search, search_proposal_no: e.target.value })} />
        </CompactFilterField>
        <CompactFilterField label="발주서 No" width={130}>
          <Input value={search.search_purchase_order_no} onChange={(e) => setSearch({ ...search, search_purchase_order_no: e.target.value })} />
        </CompactFilterField>
        <CompactFilterField label="프로젝트번호" width={150}>
          <Input value={search.project_no} onChange={(e) => setSearch({ ...search, project_no: e.target.value })} />
        </CompactFilterField>
        <CompactFilterField label="품번" width={140}>
          <Input value={search.search_part_no} onChange={(e) => setSearch({ ...search, search_part_no: e.target.value })} />
        </CompactFilterField>
        <CompactFilterField label="품명" width={160}>
          <Input value={search.search_part_name} onChange={(e) => setSearch({ ...search, search_part_name: e.target.value })} />
        </CompactFilterField>
        <CompactFilterField label="공급업체 ID" width={140}>
          <Input value={search.search_partner} onChange={(e) => setSearch({ ...search, search_partner: e.target.value })} />
        </CompactFilterField>
        <CompactFilterField label="입고결과" width={120}>
          <HardcodedSelect value={search.search_delivery_status} onChange={(v) => setSearch({ ...search, search_delivery_status: v })} options={DELIVERY_STATUS_OPTIONS} />
        </CompactFilterField>
        <CompactFilterField label="제품구분 ID" width={120}>
          <Input value={search.search_product_cd} onChange={(e) => setSearch({ ...search, search_product_cd: e.target.value })} />
        </CompactFilterField>
        <CompactFilterField label="검사여부" width={110}>
          <HardcodedSelect value={search.search_inspection_yn} onChange={(v) => setSearch({ ...search, search_inspection_yn: v })} options={INSPECTION_YN_OPTIONS} />
        </CompactFilterField>
        <CompactFilterField label="요청현황" width={120}>
          <HardcodedSelect value={search.search_request_status} onChange={(v) => setSearch({ ...search, search_request_status: v })} options={REQUEST_STATUS_OPTIONS} />
        </CompactFilterField>
        <CompactFilterField label="요청자 ID" width={120}>
          <Input value={search.request_user_id} onChange={(e) => setSearch({ ...search, request_user_id: e.target.value })} />
        </CompactFilterField>
        <CompactFilterField label="요청일" width={280}>
          <CompactDateRange
            from={search.request_start_date} setFrom={(v) => setSearch({ ...search, request_start_date: v })}
            to={search.request_end_date}     setTo={(v) => setSearch({ ...search, request_end_date: v })}
          />
        </CompactFilterField>
      </CompactFilterBar>
      <DataGrid
        gridId="quality-incoming-request"
        columns={GRID_COLUMNS}
        data={rows}
        loading={loading}
        showCheckbox
        checkedIds={selectedId ? [selectedId] : []}
        onCheckedChange={(ids) => setSelectedId(ids.length ? ids[ids.length - 1] : null)}
        selectedId={selectedId}
        onSelect={setSelectedId}
        emptyMessage="조회된 수입검사 요청이 없습니다."
        showColumnSettings
        paginationStyle="range"
        pageSizeOptions={[10, 15, 20, 50, 100]}
        showChart
        onRefresh={fetchList}
        onDownload={() => {
          if (rows.length === 0) { toast.info("내보낼 데이터가 없습니다."); return; }
          const exportRows = rows.map((r) => {
            const out: Record<string, any> = {};
            GRID_COLUMNS.forEach((c) => { out[c.label] = (r as any)[c.key] ?? ""; });
            return out;
          });
          exportToExcel(exportRows, "수입검사요청.xlsx", "수입검사요청");
        }}
      />
    </div>
  );
}
