"use client";

/**
 * ECR(Engineering Change Request) 관리 — wace_plm 의 ecrList.jsp / ecrMngFormPopUp.jsp / ecrMngDetailPopUp.jsp 포팅
 *  - 좌측 검색 필터 (연도/기종(모델)명/요청구분/작성자/상태) — wace_plm 과 동일 5 필터
 *  - 페이징 그리드 (ECR_NO, 기종(모델)명, 품번, 품명, 설변요청, 제목, 작성자, 작성일, 조치자, 조치일, 상태)
 *  - 등록·수정 모달 (변경전/변경후 textarea 2분할) / 상세 모달 / 조치완료 모달
 *  - 삭제는 status_cd='0000100'(작성중) 인 행에서만 허용
 */
import { useCallback, useEffect, useMemo, useState } from "react";
import { Plus, Trash2, Pencil, Eye, CheckCircle2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { toast } from "sonner";
import { ecrMngApi, EcrItem } from "@/lib/api/ecrMng";
import { cn } from "@/lib/utils";
import { DataGrid, DataGridColumn } from "@/components/common/DataGrid";
import { PageHeader } from "@/components/common/PageHeader";
import { CompactFilterBar, CompactFilterField } from "@/components/common/CompactFilterBar";
import { exportToExcel } from "@/lib/utils/excelExport";

type Option = { value: string; label: string };

// wace_plm ecrList.jsp + ilshin 운영 ecr_mng 컬럼 통합 그리드
const GRID_COLUMNS: DataGridColumn[] = [
  { key: "ecr_no",       label: "ECR NO",       width: "w-[130px]", frozen: true },
  { key: "product_name", label: "기종(모델)명", width: "w-[160px]" },
  { key: "equip_name",   label: "설비명",       width: "w-[140px]" },
  { key: "part_no",      label: "품번",         width: "w-[140px]" },
  { key: "part_name",    label: "품명",         width: "w-[180px]" },
  { key: "project_no",   label: "프로젝트번호", width: "w-[140px]" },
  { key: "customer_cd",  label: "고객사",       width: "w-[120px]" },
  { key: "design_dept",  label: "설계부서",     width: "w-[120px]", align: "center" },
  { key: "request_name", label: "설변요청",     width: "w-[140px]" },
  { key: "title",        label: "제목",         width: "w-[280px]" },
  { key: "writer_name",  label: "작성자",       width: "w-[110px]", align: "center" },
  { key: "reg_date",     label: "작성일",       width: "w-[115px]", align: "center" },
  { key: "check_name",   label: "조치자",       width: "w-[110px]", align: "center" },
  { key: "check_date",   label: "조치일",       width: "w-[115px]", align: "center" },
  { key: "check_result", label: "조치결과",     width: "w-[110px]", align: "center" },
  { key: "status_name",  label: "상태",         width: "w-[110px]", align: "center" },
];

const STATUS_DRAFT = "0000100"; // 작성중 (삭제/수정 허용 상태)

export default function EcrListPage() {
  // 목록 상태
  const [list, setList] = useState<EcrItem[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(100);
  const [loading, setLoading] = useState(false);
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [selected, setSelected] = useState<EcrItem | null>(null);

  // 필터 — wace_plm 기본값 = 전부 미선택(전체)
  const [year, setYear] = useState<string>("");
  const [productCode, setProductCode] = useState<string>("");
  const [requestCode, setRequestCode] = useState<string>("");
  const [writer, setWriter] = useState<string>("");
  const [statusCode, setStatusCode] = useState<string>("");

  // 옵션
  const [statusOptions, setStatusOptions] = useState<Option[]>([]);
  const [requestOptions, setRequestOptions] = useState<Option[]>([]);
  const [writerOptions, setWriterOptions] = useState<Option[]>([]);
  const [productOptions, setProductOptions] = useState<Option[]>([]);
  const [partOptions, setPartOptions] = useState<Option[]>([]);

  // 모달
  const [formOpen, setFormOpen] = useState(false);
  const [detailOpen, setDetailOpen] = useState(false);
  const [completeOpen, setCompleteOpen] = useState(false);

  // 옵션 로드 (1회)
  useEffect(() => {
    (async () => {
      try {
        const [s, r, w, p, pa] = await Promise.all([
          ecrMngApi.commCodeOptions("0000099"),
          ecrMngApi.commCodeOptions("0000090"),
          ecrMngApi.writerOptions(),
          ecrMngApi.productOptions(),
          ecrMngApi.partOptions(),
        ]);
        setStatusOptions(s);
        setRequestOptions(r);
        setWriterOptions(w);
        setProductOptions(p);
        setPartOptions(pa);
      } catch (e) {
        console.error("ECR 옵션 로드 실패", e);
      }
    })();
  }, []);

  const loadList = useCallback(async () => {
    setLoading(true);
    try {
      const res = await ecrMngApi.list({
        year: year || undefined,
        productCode: productCode || undefined,
        statusCode: statusCode || undefined,
        requestCode: requestCode || undefined,
        writer: writer || undefined,
        page,
        pageSize,
      });
      setList(res.list.map((r) => ({ ...r, id: r.objid } as any)));
      setTotal(res.pagination.total);
      setSelectedIds([]);
      setSelected(null);
    } catch (e: any) {
      toast.error(e?.message || "ECR 목록 조회 실패");
    } finally {
      setLoading(false);
    }
  }, [year, productCode, statusCode, requestCode, writer, page, pageSize]);

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

  // wace_plm: sysYear-4 ~ sysYear (5 개년)
  const yearOptions = useMemo(() => {
    const cur = new Date().getFullYear();
    return Array.from({ length: 5 }, (_, i) => String(cur - i));
  }, []);

  const handleDelete = async () => {
    // 작성중 행만 삭제 가능 (wace_plm 규칙)
    const targets = selectedIds.filter((id) => {
      const row = list.find((r) => r.objid === id);
      return row?.status_cd === STATUS_DRAFT;
    });
    if (targets.length === 0) return toast.warning("작성중 상태의 행만 삭제할 수 있습니다.");
    if (!confirm(`선택된 ${targets.length}건을 삭제하시겠습니까?`)) return;
    try {
      await ecrMngApi.remove(targets);
      toast.success("삭제되었습니다.");
      loadList();
    } catch (e: any) {
      toast.error(e?.message || "삭제 실패");
    }
  };

  const handleReset = () => {
    setYear(""); setProductCode(""); setRequestCode("");
    setWriter(""); setStatusCode("");
  };

  // status 컬러 뱃지를 적용한 row (status_name 셀을 컬러칩으로 렌더)
  const rows = useMemo(() => list, [list]);
  const gridColumns = useMemo<DataGridColumn[]>(
    () => GRID_COLUMNS.map((c) => c.key === "status_name" ? { ...c } : c),
    [],
  );

  const isDraftSelected = selected?.status_cd === STATUS_DRAFT;
  const isCompletedSelected = selected?.status_cd === "0000102";

  return (
    <div className="flex h-full flex-col overflow-hidden p-2 gap-2">
      <PageHeader
        loading={loading}
        onSearch={() => { setPage(1); loadList(); }}
        onReset={handleReset}
        actions={
          <>
            <Button size="sm" variant="destructive" className="h-8 gap-1 text-xs"
                    onClick={handleDelete} disabled={selectedIds.length === 0}>
              <Trash2 className="h-3.5 w-3.5" />삭제 ({selectedIds.length})
            </Button>
            <Button size="sm" variant="outline" className="h-8 gap-1 text-xs"
                    onClick={() => { if (selected) setDetailOpen(true); else toast.warning("상세를 볼 항목을 선택하세요."); }}
                    disabled={!selected}>
              <Eye className="h-3.5 w-3.5" />상세
            </Button>
            <Button size="sm" className="h-8 gap-1 text-xs"
                    onClick={() => { setFormOpen(true); }}
                    disabled={!!selected && !isDraftSelected}>
              {selected ? <Pencil className="h-3.5 w-3.5" /> : <Plus className="h-3.5 w-3.5" />}
              {selected ? "수정" : "등록"}
            </Button>
            <Button size="sm" className="h-8 gap-1 bg-emerald-600 hover:bg-emerald-700 text-white text-xs"
                    onClick={() => { if (!selected) toast.warning("조치완료할 항목을 선택하세요."); else if (isCompletedSelected) toast.warning("이미 적용완료된 건입니다."); else setCompleteOpen(true); }}
                    disabled={!selected || isCompletedSelected}>
              <CheckCircle2 className="h-3.5 w-3.5" />조치완료
            </Button>
          </>
        }
      />

      <CompactFilterBar totalText={<>총 {total.toLocaleString()}건</>}>
        <CompactFilterField label="연도" width={100}>
          <Select value={year || "all"} onValueChange={(v) => setYear(v === "all" ? "" : v)}>
            <SelectTrigger className="h-7 text-xs"><SelectValue placeholder="전체" /></SelectTrigger>
            <SelectContent>
              <SelectItem value="all">전체</SelectItem>
              {yearOptions.map((y) => (<SelectItem key={y} value={y}>{y}</SelectItem>))}
            </SelectContent>
          </Select>
        </CompactFilterField>
        <CompactFilterField label="기종(모델)명" width={160}>
          <Select value={productCode || "all"} onValueChange={(v) => setProductCode(v === "all" ? "" : v)}>
            <SelectTrigger className="h-7 text-xs"><SelectValue placeholder="전체" /></SelectTrigger>
            <SelectContent>
              <SelectItem value="all">전체</SelectItem>
              {productOptions.map((o) => (<SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>))}
            </SelectContent>
          </Select>
        </CompactFilterField>
        <CompactFilterField label="요청구분" width={160}>
          <Select value={requestCode || "all"} onValueChange={(v) => setRequestCode(v === "all" ? "" : v)}>
            <SelectTrigger className="h-7 text-xs"><SelectValue placeholder="전체" /></SelectTrigger>
            <SelectContent>
              <SelectItem value="all">전체</SelectItem>
              {requestOptions.map((o) => (<SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>))}
            </SelectContent>
          </Select>
        </CompactFilterField>
        <CompactFilterField label="작성자" width={160}>
          <Select value={writer || "all"} onValueChange={(v) => setWriter(v === "all" ? "" : v)}>
            <SelectTrigger className="h-7 text-xs"><SelectValue placeholder="전체" /></SelectTrigger>
            <SelectContent>
              <SelectItem value="all">전체</SelectItem>
              {writerOptions.map((o) => (<SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>))}
            </SelectContent>
          </Select>
        </CompactFilterField>
        <CompactFilterField label="상태" width={140}>
          <Select value={statusCode || "all"} onValueChange={(v) => setStatusCode(v === "all" ? "" : v)}>
            <SelectTrigger className="h-7 text-xs"><SelectValue placeholder="전체" /></SelectTrigger>
            <SelectContent>
              <SelectItem value="all">전체</SelectItem>
              {statusOptions.map((o) => (<SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>))}
            </SelectContent>
          </Select>
        </CompactFilterField>
      </CompactFilterBar>

      <DataGrid
        gridId="ecr-list"
        columns={gridColumns}
        data={rows}
        loading={loading}
        showCheckbox
        checkedIds={selectedIds}
        onCheckedChange={(ids) => {
          setSelectedIds(ids);
          if (ids.length === 0) { setSelected(null); return; }
          const last = ids[ids.length - 1];
          setSelected(rows.find((r) => r.objid === last) ?? null);
        }}
        selectedId={selected ? selected.objid : null}
        onSelect={(id) => setSelected(rows.find((r) => r.objid === id) ?? null)}
        onRowDoubleClick={(row) => {
          setSelected(row as EcrItem);
          if (row.status_cd === STATUS_DRAFT) setFormOpen(true);
          else setDetailOpen(true);
        }}
        emptyMessage="조회된 ECR이 없습니다."
        showColumnSettings
        paginationStyle="range"
        pageSizeOptions={[10, 15, 20, 50, 100]}
        showChart
        onRefresh={loadList}
        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, "ECR관리.xlsx", "ECR관리");
        }}
      />

      {/* 등록/수정 모달 */}
      <EcrFormModal
        open={formOpen}
        onClose={() => setFormOpen(false)}
        onSaved={() => { setFormOpen(false); loadList(); }}
        editing={selected}
        productOptions={productOptions}
        partOptions={partOptions}
        requestOptions={requestOptions}
      />

      {/* 상세 모달 */}
      <EcrDetailModal
        open={detailOpen}
        onClose={() => setDetailOpen(false)}
        item={selected}
        statusOptions={statusOptions}
      />

      {/* 조치완료 모달 */}
      <EcrCompleteModal
        open={completeOpen}
        onClose={() => setCompleteOpen(false)}
        onCompleted={() => { setCompleteOpen(false); loadList(); }}
        item={selected}
      />
    </div>
  );
}

// ── 등록/수정 모달 ───────────────────────────────────────────
function EcrFormModal({
  open, onClose, onSaved, editing, productOptions, partOptions, requestOptions,
}: {
  open: boolean;
  onClose: () => void;
  onSaved: () => void;
  editing: EcrItem | null;
  productOptions: Option[];
  partOptions: Option[];
  requestOptions: Option[];
}) {
  const isEdit = !!editing?.objid;
  const [title, setTitle] = useState("");
  const [productObjid, setProductObjid] = useState("");
  const [partObjid, setPartObjid] = useState("");
  const [requestCodes, setRequestCodes] = useState<Set<string>>(new Set());
  const [beforeContents, setBeforeContents] = useState("");
  const [afterContents, setAfterContents] = useState("");
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (open) {
      setTitle(editing?.title || "");
      setProductObjid(editing?.product_objid || "");
      setPartObjid(editing?.part_objid || "");
      setRequestCodes(new Set((editing?.request_cd || "").split(",").map((s) => s.trim()).filter(Boolean)));
      setBeforeContents(editing?.before_contents || "");
      setAfterContents(editing?.after_contents || "");
    }
  }, [open, editing]);

  const handleSave = async () => {
    if (!productObjid) return toast.warning("기종(모델)을 선택하세요.");
    if (!partObjid) return toast.warning("품번을 선택하세요.");
    if (!title.trim()) return toast.warning("제목을 입력하세요.");
    setSaving(true);
    try {
      await ecrMngApi.merge({
        objId: editing?.objid,
        title,
        product_objid: productObjid || null,
        part_objid: partObjid || null,
        request_codeArr: Array.from(requestCodes).join(","),
        before_contents: beforeContents,
        after_contents: afterContents,
      });
      toast.success("저장되었습니다.");
      onSaved();
    } catch (e: any) {
      toast.error(e?.message || "저장 실패");
    } finally {
      setSaving(false);
    }
  };

  // 선택된 부품의 품명 표시 (wace_plm 의 part_name 자동 표시 모방)
  const selectedPart = partOptions.find((p) => p.value === partObjid);

  return (
    <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
      <DialogContent className="max-w-4xl">
        <DialogHeader>
          <DialogTitle>설계변경요청서 (Engineering Change Request) {isEdit ? `— ${editing?.ecr_no}` : ""}</DialogTitle>
        </DialogHeader>
        <div className="space-y-3">
          {/* 1행 : 기종(모델) / 품번 / 품명 / ECR_NO */}
          <div className="grid grid-cols-4 gap-2 rounded border bg-muted/10 p-2">
            <div className="space-y-1">
              <Label className="text-[11px]">기종(모델) <span className="text-destructive">*</span></Label>
              <Select value={productObjid || "none"} onValueChange={(v) => setProductObjid(v === "none" ? "" : v)}>
                <SelectTrigger className="h-8 text-xs"><SelectValue placeholder="선택" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="none">선택 안 함</SelectItem>
                  {productOptions.map((o) => (<SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-1">
              <Label className="text-[11px]">품번 <span className="text-destructive">*</span></Label>
              <Select value={partObjid || "none"} onValueChange={(v) => setPartObjid(v === "none" ? "" : v)}>
                <SelectTrigger className="h-8 text-xs"><SelectValue placeholder="선택" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="none">선택 안 함</SelectItem>
                  {partOptions.map((o) => (<SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-1">
              <Label className="text-[11px]">품명</Label>
              <div className="flex h-8 items-center rounded-md border bg-muted/30 px-2 text-xs">
                {selectedPart?.label?.replace(/^\S+\s*/, "") || editing?.part_name || "-"}
              </div>
            </div>
            <div className="space-y-1">
              <Label className="text-[11px]">ECR NO</Label>
              <div className="flex h-8 items-center rounded-md border bg-muted/30 px-2 text-xs font-mono">
                {editing?.ecr_no || "(자동채번)"}
              </div>
            </div>
          </div>

          {/* 설변요청 (다중) */}
          <div className="space-y-1">
            <Label className="text-xs">설변요청</Label>
            <div className="flex flex-wrap gap-1.5 rounded-md border bg-muted/20 p-2">
              {requestOptions.length === 0 ? (
                <span className="text-xs text-muted-foreground">요청코드(0000090) 자식 코드가 없습니다.</span>
              ) : (
                requestOptions.map((o) => {
                  const active = requestCodes.has(o.value);
                  return (
                    <button
                      key={o.value}
                      type="button"
                      onClick={() => {
                        const next = new Set(requestCodes);
                        if (active) next.delete(o.value); else next.add(o.value);
                        setRequestCodes(next);
                      }}
                      className={cn(
                        "rounded-full border px-2.5 py-0.5 text-[11px] transition",
                        active
                          ? "border-primary bg-primary text-primary-foreground"
                          : "border-border bg-background hover:border-primary/50",
                      )}
                    >
                      {o.label}
                    </button>
                  );
                })
              )}
            </div>
          </div>

          {/* 제목 */}
          <div className="space-y-1">
            <Label className="text-xs">제목 <span className="text-destructive">*</span></Label>
            <Input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="ECR 제목" className="h-8 text-xs" />
          </div>

          {/* 변경전 / 변경후 (wace_plm 2분할 레이아웃) */}
          <div className="grid grid-cols-2 gap-2 rounded border border-black/60 p-2">
            <div className="space-y-1">
              <Label className="text-xs font-bold">[변경전]</Label>
              <Textarea
                value={beforeContents}
                onChange={(e) => setBeforeContents(e.target.value)}
                placeholder="변경전"
                className="min-h-[200px] text-xs"
                rows={9}
              />
            </div>
            <div className="space-y-1">
              <Label className="text-xs font-bold">[변경후]</Label>
              <Textarea
                value={afterContents}
                onChange={(e) => setAfterContents(e.target.value)}
                placeholder="변경후"
                className="min-h-[200px] text-xs"
                rows={9}
              />
            </div>
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" size="sm" className="h-8 text-xs" onClick={onClose} disabled={saving}>닫기</Button>
          <Button size="sm" className="h-8 text-xs" onClick={handleSave} disabled={saving}>
            {saving ? "저장 중..." : (isEdit ? "수정" : "저장")}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

// ── 상세 모달 ────────────────────────────────────────────────
function EcrDetailModal({
  open, onClose, item, statusOptions,
}: {
  open: boolean;
  onClose: () => void;
  item: EcrItem | null;
  statusOptions: Option[];
}) {
  return (
    <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
      <DialogContent className="max-w-4xl">
        <DialogHeader>
          <DialogTitle>설계변경요청서 (상세) — {item?.ecr_no}</DialogTitle>
        </DialogHeader>
        {item && (
          <div className="space-y-2 text-xs">
            <div className="grid grid-cols-4 gap-2 rounded border bg-muted/10 p-2">
              <Field label="기종(모델)" value={item.product_name || "-"} />
              <Field label="품번" value={item.part_no || "-"} />
              <Field label="품명" value={item.part_name || "-"} />
              <Field label="ECR NO" value={item.ecr_no} mono />
            </div>
            <Field label="설변요청" value={item.request_name || "-"} block />
            <Field label="제목" value={item.title} block />
            <div className="grid grid-cols-2 gap-2 rounded border border-black/60 p-2">
              <Field label="[변경전]" value={item.before_contents || "-"} block dense />
              <Field label="[변경후]" value={item.after_contents || "-"} block dense />
            </div>
            <div className="grid grid-cols-4 gap-2">
              <Field label="작성자" value={item.writer_name || item.writer || "-"} />
              <Field label="작성일" value={item.reg_date || "-"} />
              <Field label="조치자" value={item.check_name || "-"} />
              <Field label="조치일" value={item.check_date || "-"} />
            </div>
            <Field
              label="상태"
              value={item.status_name || statusOptions.find((s) => s.value === item.status_cd)?.label || item.status_cd}
            />
          </div>
        )}
        <DialogFooter>
          <Button variant="outline" size="sm" className="h-8 text-xs" onClick={onClose}>닫기</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

function Field({ label, value, block, mono, dense }: { label: string; value?: React.ReactNode; block?: boolean; mono?: boolean; dense?: boolean }) {
  return (
    <div className={cn("rounded border bg-muted/20 p-1.5", block && "col-span-full")}>
      <div className="text-[10px] font-medium uppercase text-muted-foreground">{label}</div>
      <div className={cn("mt-0.5 text-xs", block && "whitespace-pre-wrap", mono && "font-mono", dense && "min-h-[120px]")}>{value || "-"}</div>
    </div>
  );
}

// ── 조치완료 모달 ────────────────────────────────────────────
function EcrCompleteModal({
  open, onClose, onCompleted, item,
}: {
  open: boolean;
  onClose: () => void;
  onCompleted: () => void;
  item: EcrItem | null;
}) {
  const [afterContents, setAfterContents] = useState("");
  const [saving, setSaving] = useState(false);

  useEffect(() => { if (open) setAfterContents(item?.after_contents || ""); }, [open, item]);

  const handleComplete = async () => {
    if (!item) return;
    if (!afterContents.trim()) return toast.warning("조치내역을 입력해주세요.");
    if (!confirm("조치완료 하시겠습니까?")) return;
    setSaving(true);
    try {
      await ecrMngApi.complete(item.objid, afterContents);
      toast.success("저장되었습니다.");
      onCompleted();
    } catch (e: any) {
      toast.error(e?.message || "조치완료 실패");
    } finally {
      setSaving(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>ECR 조치완료 — {item?.ecr_no}</DialogTitle>
        </DialogHeader>
        <div className="space-y-2">
          <div className="rounded border bg-muted/30 p-2 text-xs">
            <span className="font-medium">제목:</span> {item?.title}
          </div>
          <div className="space-y-1">
            <Label className="text-xs">조치내역 <span className="text-destructive">*</span></Label>
            <Textarea value={afterContents} onChange={(e) => setAfterContents(e.target.value)} className="min-h-[180px] text-xs" rows={8} />
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" size="sm" className="h-8 text-xs" onClick={onClose} disabled={saving}>취소</Button>
          <Button size="sm" className="h-8 gap-1 text-xs" onClick={handleComplete} disabled={saving}>
            <CheckCircle2 className="h-3.5 w-3.5" /> {saving ? "처리 중..." : "조치완료"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
