"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import {
  Loader2,
  Settings,
  Plus,
  Pencil,
  Trash2,
  Search,
  RotateCcw,
  Wrench,
} from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  ResizablePanelGroup,
  ResizablePanel,
  ResizableHandle,
} from "@/components/ui/resizable";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Checkbox } from "@/components/ui/checkbox";
import {
  getProcessList,
  createProcess,
  updateProcess,
  deleteProcesses,
  getProcessEquipments,
  addProcessEquipment,
  removeProcessEquipment,
  getEquipmentList,
  type ProcessMaster,
  type ProcessEquipment,
  type Equipment,
} from "@/lib/api/processInfo"; // API: /process-info/*
import { getCategoryValues } from "@/lib/api/tableCategoryValue";

const ALL_VALUE = "__all__";

export function ProcessMasterTab() {
  const [processes, setProcesses] = useState<ProcessMaster[]>([]);
  const [equipmentMaster, setEquipmentMaster] = useState<Equipment[]>([]);
  const [processTypeOptions, setProcessTypeOptions] = useState<{ valueCode: string; valueLabel: string }[]>([]);
  const [loadingInitial, setLoadingInitial] = useState(true);
  const [loadingList, setLoadingList] = useState(false);
  const [loadingEquipments, setLoadingEquipments] = useState(false);

  const [filterCode, setFilterCode] = useState("");
  const [filterName, setFilterName] = useState("");
  const [filterType, setFilterType] = useState<string>(ALL_VALUE);
  const [filterUseYn, setFilterUseYn] = useState<string>(ALL_VALUE);

  const [selectedProcess, setSelectedProcess] = useState<ProcessMaster | null>(null);
  const [selectedIds, setSelectedIds] = useState<Set<string>>(() => new Set());

  const [processEquipments, setProcessEquipments] = useState<ProcessEquipment[]>([]);
  const [equipmentPick, setEquipmentPick] = useState<string>("");
  const [addingEquipment, setAddingEquipment] = useState(false);

  const [formOpen, setFormOpen] = useState(false);
  const [formMode, setFormMode] = useState<"add" | "edit">("add");
  const [savingForm, setSavingForm] = useState(false);
  const [formProcessCode, setFormProcessCode] = useState("");
  const [formProcessName, setFormProcessName] = useState("");
  const [formProcessType, setFormProcessType] = useState<string>("");
  const [formStandardTime, setFormStandardTime] = useState("");
  const [formWorkerCount, setFormWorkerCount] = useState("");
  const [formUseYn, setFormUseYn] = useState("");
  const [editingId, setEditingId] = useState<string | null>(null);

  const [deleteOpen, setDeleteOpen] = useState(false);
  const [deleting, setDeleting] = useState(false);

  const processTypeMap = useMemo(() => {
    const m = new Map<string, string>();
    processTypeOptions.forEach((o) => m.set(o.valueCode, o.valueLabel));
    return m;
  }, [processTypeOptions]);

  const getProcessTypeLabel = useCallback(
    (code: string) => processTypeMap.get(code) ?? code,
    [processTypeMap]
  );

  const loadProcesses = useCallback(async () => {
    setLoadingList(true);
    try {
      const res = await getProcessList({
        processCode: filterCode.trim() || undefined,
        processName: filterName.trim() || undefined,
        processType: filterType === ALL_VALUE ? undefined : filterType,
        useYn: filterUseYn === ALL_VALUE ? undefined : filterUseYn,
      });
      if (!res.success) {
        toast.error(res.message || "공정 목록을 불러오지 못했어요");
        return;
      }
      setProcesses(res.data ?? []);
    } finally {
      setLoadingList(false);
    }
  }, [filterCode, filterName, filterType, filterUseYn]);

  const loadInitial = useCallback(async () => {
    setLoadingInitial(true);
    try {
      const [procRes, eqRes] = await Promise.all([getProcessList(), getEquipmentList()]);
      if (!procRes.success) {
        toast.error(procRes.message || "공정 목록을 불러오지 못했어요");
      } else {
        setProcesses(procRes.data ?? []);
      }
      if (!eqRes.success) {
        toast.error(eqRes.message || "설비 목록을 불러오지 못했어요");
      } else {
        setEquipmentMaster(eqRes.data ?? []);
      }
      const ptRes = await getCategoryValues("process_mng", "process_type");
      if (ptRes.success && "data" in ptRes && Array.isArray(ptRes.data)) {
        const activeValues = ptRes.data.filter((v: any) => v.isActive !== false);
        const seen = new Set<string>();
        const unique = activeValues.filter((v: any) => {
          if (seen.has(v.valueCode)) return false;
          seen.add(v.valueCode);
          return true;
        });
        setProcessTypeOptions(unique.map((v: any) => ({ valueCode: v.valueCode, valueLabel: v.valueLabel })));
      }
    } finally {
      setLoadingInitial(false);
    }
  }, []);

  useEffect(() => {
    void loadInitial();
  }, [loadInitial]);

  useEffect(() => {
    setSelectedProcess((prev) => {
      if (!prev) return prev;
      if (!processes.some((p) => p.id === prev.id)) return null;
      return prev;
    });
  }, [processes]);

  useEffect(() => {
    setEquipmentPick("");
  }, [selectedProcess?.id]);

  useEffect(() => {
    if (!selectedProcess) {
      setProcessEquipments([]);
      return;
    }
    let cancelled = false;
    setLoadingEquipments(true);
    void (async () => {
      const res = await getProcessEquipments(selectedProcess.process_code);
      if (cancelled) return;
      if (!res.success) {
        toast.error(res.message || "공정 설비를 불러오지 못했어요");
        setProcessEquipments([]);
      } else {
        setProcessEquipments(res.data ?? []);
      }
      setLoadingEquipments(false);
    })();
    return () => {
      cancelled = true;
    };
  }, [selectedProcess?.process_code]);

  const handleResetFilters = () => {
    setFilterCode("");
    setFilterName("");
    setFilterType(ALL_VALUE);
    setFilterUseYn(ALL_VALUE);
  };

  const handleSearch = () => {
    void loadProcesses();
  };

  const openAdd = () => {
    setFormMode("add");
    setEditingId(null);
    setFormProcessCode("");
    setFormProcessName("");
    setFormProcessType(processTypeOptions[0]?.valueCode ?? "");
    setFormStandardTime("");
    setFormWorkerCount("");
    setFormUseYn("Y");
    setFormOpen(true);
  };

  const openEdit = () => {
    if (!selectedProcess) {
      toast.message("수정할 공정을 좌측 목록에서 선택해주세요");
      return;
    }
    setFormMode("edit");
    setEditingId(selectedProcess.id);
    setFormProcessCode(selectedProcess.process_code);
    setFormProcessName(selectedProcess.process_name);
    setFormProcessType(selectedProcess.process_type);
    setFormStandardTime(selectedProcess.standard_time ?? "");
    setFormWorkerCount(selectedProcess.worker_count ?? "");
    setFormUseYn(selectedProcess.use_yn);
    setFormOpen(true);
  };

  const submitForm = async () => {
    if (!formProcessName.trim()) {
      toast.error("공정명을 입력해주세요");
      return;
    }

    setSavingForm(true);
    try {
      if (formMode === "add") {
        const res = await createProcess({
          process_name: formProcessName.trim(),
          process_type: formProcessType,
          standard_time: formStandardTime.trim() || "0",
          worker_count: formWorkerCount.trim() || "0",
          use_yn: formUseYn,
        });
        if (!res.success || !res.data) {
          toast.error(res.message || "등록에 실패했어요");
          return;
        }
        toast.success("공정이 등록되었어요");
        setFormOpen(false);
        await loadProcesses();
        setSelectedProcess(res.data);
        setSelectedIds(new Set());
      } else if (editingId) {
        const res = await updateProcess(editingId, {
          process_name: formProcessName.trim(),
          process_type: formProcessType,
          standard_time: formStandardTime.trim() || "0",
          worker_count: formWorkerCount.trim() || "0",
          use_yn: formUseYn,
        });
        if (!res.success || !res.data) {
          toast.error(res.message || "수정에 실패했어요");
          return;
        }
        toast.success("공정이 수정되었어요");
        setFormOpen(false);
        await loadProcesses();
        setSelectedProcess(res.data);
      }
    } finally {
      setSavingForm(false);
    }
  };

  const openDelete = () => {
    if (selectedIds.size === 0) {
      toast.message("삭제할 공정을 체크박스로 선택해주세요");
      return;
    }
    setDeleteOpen(true);
  };

  const confirmDelete = async () => {
    const ids = Array.from(selectedIds);
    setDeleting(true);
    try {
      const res = await deleteProcesses(ids);
      if (!res.success) {
        toast.error(res.message || "삭제에 실패했어요");
        return;
      }
      toast.success(`${ids.length}건 삭제되었어요`);
      setDeleteOpen(false);
      setSelectedIds(new Set());
      if (selectedProcess && ids.includes(selectedProcess.id)) {
        setSelectedProcess(null);
      }
      await loadProcesses();
    } finally {
      setDeleting(false);
    }
  };

  const availableEquipments = useMemo(() => {
    const used = new Set(processEquipments.map((e) => e.equipment_code));
    return equipmentMaster.filter((e) => !used.has(e.equipment_code));
  }, [equipmentMaster, processEquipments]);

  const handleAddEquipment = async () => {
    if (!selectedProcess) return;
    if (!equipmentPick) {
      toast.message("추가할 설비를 선택해주세요");
      return;
    }
    setAddingEquipment(true);
    try {
      const res = await addProcessEquipment({
        process_code: selectedProcess.process_code,
        equipment_code: equipmentPick,
      });
      if (!res.success) {
        toast.error(res.message || "설비 추가에 실패했어요");
        return;
      }
      toast.success("설비가 등록되었어요");
      setEquipmentPick("");
      const listRes = await getProcessEquipments(selectedProcess.process_code);
      if (listRes.success && listRes.data) setProcessEquipments(listRes.data);
    } finally {
      setAddingEquipment(false);
    }
  };

  const handleRemoveEquipment = async (row: ProcessEquipment) => {
    const res = await removeProcessEquipment(row.id);
    if (!res.success) {
      toast.error(res.message || "설비 제거에 실패했어요");
      return;
    }
    toast.success("설비가 제거되었어요");
    if (selectedProcess) {
      const listRes = await getProcessEquipments(selectedProcess.process_code);
      if (listRes.success && listRes.data) setProcessEquipments(listRes.data);
    }
  };

  const listBusy = loadingInitial || loadingList;

  // 표시용 데이터
  const processGridData = useMemo(
    () =>
      processes.map((p) => ({
        ...p,
        process_type_display: getProcessTypeLabel(p.process_type),
        use_yn_display: p.use_yn === "Y" ? "사용" : "미사용",
      })),
    [processes, getProcessTypeLabel]
  );

  return (
    <div className="flex h-full flex-col">
      <ResizablePanelGroup direction="horizontal" className="min-h-0 flex-1">
        {/* 좌측: 공정 목록 */}
        <ResizablePanel defaultSize={50} minSize={30}>
          <div className="flex h-full flex-col">
            {/* 패널 헤더 */}
            <div className="flex items-center gap-2 border-b bg-muted/30 px-4 py-2">
              <Settings className="h-4 w-4 text-muted-foreground" />
              <span className="text-sm font-semibold">공정 마스터</span>
              <Badge variant="secondary" className="font-mono text-xs">
                {processes.length}건
              </Badge>
            </div>

            {/* 필터 바 */}
            <div className="flex flex-wrap items-center gap-2 border-b px-3 py-2">
              <Input value={filterCode} onChange={(e) => setFilterCode(e.target.value)} placeholder="공정코드" className="h-8 w-[110px] text-xs" />
              <Input value={filterName} onChange={(e) => setFilterName(e.target.value)} placeholder="공정명" className="h-8 w-[130px] text-xs" />
              <Select value={filterType} onValueChange={setFilterType}>
                <SelectTrigger className="h-8 w-[110px] text-xs">
                  <SelectValue placeholder="유형 전체" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value={ALL_VALUE}>전체</SelectItem>
                  {processTypeOptions.map((o, idx) => (
                    <SelectItem key={`pt-filter-${idx}`} value={o.valueCode}>{o.valueLabel}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Select value={filterUseYn} onValueChange={setFilterUseYn}>
                <SelectTrigger className="h-8 w-[100px] text-xs">
                  <SelectValue placeholder="사용 전체" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value={ALL_VALUE}>전체</SelectItem>
                  <SelectItem value="Y">사용</SelectItem>
                  <SelectItem value="N">미사용</SelectItem>
                </SelectContent>
              </Select>
              <div className="flex-1" />
              {listBusy && <Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" />}
              <Button size="sm" className="h-8 gap-1 text-xs" onClick={handleSearch} disabled={listBusy}>
                <Search className="h-3 w-3" />조회
              </Button>
              <Button variant="ghost" size="sm" className="h-8 gap-1 text-xs text-muted-foreground" onClick={handleResetFilters}>
                <RotateCcw className="h-3 w-3" />초기화
              </Button>
            </div>

            {/* 액션 바 */}
            <div className="flex items-center justify-end gap-2 border-b bg-muted/30 px-4 py-2">
              <Button size="sm" onClick={openAdd}>
                <Plus className="mr-1 h-3.5 w-3.5" />
                공정 추가
              </Button>
              <Button variant="secondary" size="sm" onClick={openEdit}>
                <Pencil className="mr-1 h-3.5 w-3.5" />
                수정
              </Button>
              <Button variant="destructive" size="sm" onClick={openDelete}>
                <Trash2 className="mr-1 h-3.5 w-3.5" />
                삭제
              </Button>
            </div>

            {/* 공정 목록 테이블 */}
            <div className="min-h-0 flex-1 overflow-auto">
              {listBusy ? (
                <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
                  <Loader2 className="h-7 w-7 animate-spin" />
                  <p className="mt-2 text-sm">불러오는 중...</p>
                </div>
              ) : processGridData.length === 0 ? (
                <p className="py-8 text-center text-sm text-muted-foreground">조회된 공정이 없어요</p>
              ) : (
                <Table>
                  <TableHeader className="sticky top-0 bg-muted/90 z-10">
                    <TableRow>
                      <TableHead className="w-10 text-muted-foreground">
                        <Checkbox
                          checked={selectedIds.size === processGridData.length && processGridData.length > 0}
                          onCheckedChange={(checked) => {
                            if (checked) setSelectedIds(new Set(processGridData.map((r) => r.id)));
                            else setSelectedIds(new Set());
                          }}
                        />
                      </TableHead>
                      <TableHead className="w-[130px] text-muted-foreground">공정코드</TableHead>
                      <TableHead className="text-muted-foreground">공정명</TableHead>
                      <TableHead className="w-[120px] text-muted-foreground">공정유형</TableHead>
                      <TableHead className="w-[110px] text-right text-muted-foreground">표준시간(분)</TableHead>
                      <TableHead className="w-[90px] text-right text-muted-foreground">작업인원</TableHead>
                      <TableHead className="w-[90px] text-center text-muted-foreground">사용여부</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {processGridData.map((row) => (
                      <TableRow
                        key={row.id}
                        data-state={selectedProcess?.id === row.id ? "selected" : undefined}
                        className="cursor-pointer hover:bg-muted/30"
                        onClick={() => {
                          const proc = processes.find((p) => p.id === row.id);
                          setSelectedProcess(proc || null);
                        }}
                      >
                        <TableCell onClick={(e) => e.stopPropagation()}>
                          <Checkbox
                            checked={selectedIds.has(row.id)}
                            onCheckedChange={(checked) => {
                              setSelectedIds((prev) => {
                                const next = new Set(prev);
                                if (checked) next.add(row.id);
                                else next.delete(row.id);
                                return next;
                              });
                            }}
                          />
                        </TableCell>
                        <TableCell className="font-mono text-xs">{row.process_code}</TableCell>
                        <TableCell>{row.process_name}</TableCell>
                        <TableCell>{row.process_type_display}</TableCell>
                        <TableCell className="text-right">{row.standard_time}</TableCell>
                        <TableCell className="text-right">{row.worker_count}</TableCell>
                        <TableCell className="text-center">{row.use_yn_display}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              )}
            </div>
          </div>
        </ResizablePanel>

        <ResizableHandle withHandle />

        {/* 우측: 공정별 설비 */}
        <ResizablePanel defaultSize={50} minSize={30}>
          <div className="flex h-full flex-col">
            {/* 패널 헤더 */}
            <div className="flex items-center gap-2 border-b bg-muted/30 px-4 py-2">
              <Wrench className="h-4 w-4 text-muted-foreground" />
              <div className="min-w-0 flex-1">
                <p className="truncate text-sm font-semibold">공정별 사용설비</p>
                {selectedProcess ? (
                  <p className="truncate text-xs text-muted-foreground">
                    {selectedProcess.process_name} ({selectedProcess.process_code})
                  </p>
                ) : (
                  <p className="text-xs text-muted-foreground">공정을 선택해주세요</p>
                )}
              </div>
            </div>

            {!selectedProcess ? (
              <div className="flex flex-1 flex-col items-center justify-center gap-2 text-center text-muted-foreground">
                <Settings className="h-10 w-10 opacity-40" />
                <p className="text-sm font-medium text-foreground">좌측에서 공정을 선택해주세요</p>
                <p className="max-w-xs text-xs">
                  목록 행을 클릭하면 이 공정에 연결된 설비를 관리할 수 있어요
                </p>
              </div>
            ) : (
              <div className="flex min-h-0 flex-1 flex-col gap-3 p-4">
                <div className="flex items-end gap-2">
                  <div className="min-w-0 flex-1 space-y-1">
                    <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">설비 선택</Label>
                    <Select
                      key={selectedProcess.id}
                      value={equipmentPick || undefined}
                      onValueChange={setEquipmentPick}
                      disabled={addingEquipment || availableEquipments.length === 0}
                    >
                      <SelectTrigger className="h-9" size="sm">
                        <SelectValue placeholder="설비를 선택해주세요" />
                      </SelectTrigger>
                      <SelectContent>
                        {availableEquipments.map((eq) => (
                          <SelectItem key={eq.id} value={eq.equipment_code}>
                            {eq.equipment_code} · {eq.equipment_name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  <Button
                    size="sm"
                    onClick={() => void handleAddEquipment()}
                    disabled={addingEquipment || !equipmentPick}
                  >
                    {addingEquipment ? (
                      <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" />
                    ) : (
                      <Plus className="mr-1 h-3.5 w-3.5" />
                    )}
                    추가
                  </Button>
                </div>

                <div className="min-h-0 flex-1 overflow-auto">
                  {loadingEquipments ? (
                    <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
                      <Loader2 className="h-7 w-7 animate-spin" />
                      <p className="mt-2 text-sm">설비 목록을 불러오고 있어요...</p>
                    </div>
                  ) : processEquipments.length === 0 ? (
                    <p className="py-8 text-center text-sm text-muted-foreground">
                      등록된 설비가 없어요. 상단에서 설비를 추가해주세요.
                    </p>
                  ) : (
                    <ul className="space-y-2">
                      {processEquipments.map((pe) => (
                        <li key={pe.id} className="flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/30">
                          <div className="min-w-0 flex-1">
                            <p className="truncate text-sm font-medium">{pe.equipment_code}</p>
                            <p className="truncate text-xs text-muted-foreground">{pe.equipment_name || "설비명 없음"}</p>
                          </div>
                          <Button variant="ghost" size="sm" onClick={() => void handleRemoveEquipment(pe)}>
                            <Trash2 className="mr-1 h-3.5 w-3.5" />
                            제거
                          </Button>
                        </li>
                      ))}
                    </ul>
                  )}
                </div>
              </div>
            )}
          </div>
        </ResizablePanel>
      </ResizablePanelGroup>

      {/* 공정 등록/수정 모달 */}
      <Dialog open={formOpen} onOpenChange={setFormOpen}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>{formMode === "add" ? "공정 추가" : "공정 수정"}</DialogTitle>
            <DialogDescription>공정 마스터 정보를 입력해주세요</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-1">
              <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                공정명 <span className="text-destructive">*</span>
              </Label>
              <Input
                value={formProcessName}
                onChange={(e) => setFormProcessName(e.target.value)}
                placeholder="공정명을 입력해주세요"
                className="h-9"
              />
            </div>
            <div className="space-y-1">
              <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">공정유형</Label>
              <Select value={formProcessType} onValueChange={setFormProcessType}>
                <SelectTrigger className="h-9" size="sm">
                  <SelectValue placeholder="선택해주세요" />
                </SelectTrigger>
                <SelectContent>
                  {processTypeOptions.map((o, idx) => (
                    <SelectItem key={`pt-form-${idx}`} value={o.valueCode}>{o.valueLabel}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-1">
              <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">표준작업시간(분)</Label>
              <Input
                value={formStandardTime}
                onChange={(e) => setFormStandardTime(e.target.value)}
                placeholder="0"
                inputMode="numeric"
                className="h-9"
              />
            </div>
            <div className="space-y-1">
              <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">작업인원수</Label>
              <Input
                value={formWorkerCount}
                onChange={(e) => setFormWorkerCount(e.target.value)}
                placeholder="0"
                inputMode="numeric"
                className="h-9"
              />
            </div>
            <div className="space-y-1">
              <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">사용여부</Label>
              <Select value={formUseYn} onValueChange={setFormUseYn}>
                <SelectTrigger className="h-9" size="sm">
                  <SelectValue placeholder="선택해주세요" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="Y">사용</SelectItem>
                  <SelectItem value="N">미사용</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setFormOpen(false)} disabled={savingForm}>취소</Button>
            <Button onClick={() => void submitForm()} disabled={savingForm}>
              {savingForm && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              저장해요
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 삭제 확인 */}
      <Dialog open={deleteOpen} onOpenChange={setDeleteOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>공정 삭제</DialogTitle>
            <DialogDescription>
              선택한 {selectedIds.size}건의 공정을 삭제해요. 연결된 공정-설비 매핑도 함께 삭제돼요. 이 작업은 되돌릴 수 없어요.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter className="gap-2">
            <Button variant="outline" onClick={() => setDeleteOpen(false)} disabled={deleting}>취소</Button>
            <Button variant="destructive" onClick={() => void confirmDelete()} disabled={deleting}>
              {deleting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              삭제해요
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
