"use client"; import { DeleteButton } from "@suphark/ui/components/shared/button/delete-button"; import { useUiText } from "@suphark/ui/components/shared/ui-text"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger, } from "@suphark/ui/components/ui/alert-dialog"; import { buttonVariants } from "@suphark/ui/components/ui/button"; import { errorMessage, failedResult, isNavigationError } from "@suphark/ui/lib/action-result"; import { cn } from "@suphark/ui/lib/utils"; import type { Table } from "@tanstack/react-table"; import { useState, useTransition } from "react"; import { toast } from "sonner"; import { StatusLoading } from "../semantic-icons"; interface DeleteManyButtonProps { table: Table; deleteAction: (data: { ids: string[] }) => Promise; onSuccess?: () => void; /** คำเรียกสิ่งที่ลบ เช่น "ผู้ใช้" — ค่าเริ่มต้น `UiText.deleteMany.items` ("รายการ") */ itemDescription?: string; responsive?: boolean; } export function DeleteManyButton({ table, deleteAction, onSuccess, itemDescription, responsive = false, }: DeleteManyButtonProps) { const uiText = useUiText(); const text = uiText.deleteMany; const items = itemDescription ?? text?.items ?? "รายการ"; const [isPending, startTransition] = useTransition(); const [open, setOpen] = useState(false); const selectedRows = table.getFilteredSelectedRowModel().rows; if (selectedRows.length === 0) { return null; } const count = selectedRows.length; const fill = (template: string, n = count) => template.replaceAll("{count}", String(n)).replaceAll("{items}", items); function handleDelete() { startTransition(async () => { const ids = selectedRows.map((row) => (row.original as { id: string }).id); const failText = uiText.actionFailed ?? "ดำเนินการไม่สำเร็จ"; try { const result: unknown = await deleteAction({ ids }); // { ok: false } / { error } = ล้มเหลว (ไม่มีข้อความก็ไม่นับเป็นสำเร็จ) const failed = failedResult(result, failText) ?? (result && typeof result === "object" && "error" in result && result.error ? String(result.error) : null); if (failed) { toast.error(failed); return; } toast.success(fill(text?.success ?? "ลบ {count} {items}แล้ว", ids.length)); // AlertDialogAction ของ Base UI เป็น Button ธรรมดา (ไม่ใช่ Close) → ต้องปิดเอง + ล้างแถวที่เลือก setOpen(false); table.resetRowSelection(); onSuccess?.(); } catch (err) { // redirect() ใน server action = นำทางอยู่แล้ว ไม่ใช่ error ("NEXT_REDIRECT") if (isNavigationError(err)) return; toast.error(errorMessage(err, failText)); } }); } return ( !isPending && setOpen(o)}> }> {fill(text?.trigger ?? "ลบ ({count})")} {fill(text?.title ?? "ลบ {count} {items}ที่เลือก?")} {fill(text?.description ?? "{items}ที่เลือกจะถูกลบถาวร และย้อนกลับไม่ได้")} {uiText.cancel} {isPending && } {uiText.buttons?.delete ?? "ลบ"} ); }