78 lines
2.3 KiB
TypeScript
78 lines
2.3 KiB
TypeScript
"use client"
|
|||
|
|
|
||
|
|
import { useState } from "react"
|
||
|
|
import { useRouter } from "next/navigation"
|
||
|
|
import { Trash2 } from "lucide-react"
|
||
|
|
import { toast } from "sonner"
|
||
|
|
import { ConfirmModal } from "@/components/ui/confirm-modal"
|
||
|
|
|
||
|
|
interface DeleteTenantButtonProps {
|
||
|
|
tenantId: string
|
||
|
|
tenantName?: string
|
||
|
|
/** When set, refresh in place instead of navigating to the tenants list. */
|
||
|
|
refreshOnly?: boolean
|
||
|
|
/** Compact icon-only variant for table rows. */
|
||
|
|
compact?: boolean
|
||
|
|
}
|
||
|
|
|
||
|
|
export function DeleteTenantButton({ tenantId, tenantName, refreshOnly, compact }: DeleteTenantButtonProps) {
|
||
|
|
const router = useRouter()
|
||
|
|
const [open, setOpen] = useState(false)
|
||
|
|
const [loading, setLoading] = useState(false)
|
||
|
|
|
||
|
|
async function handleDelete() {
|
||
|
|
setLoading(true)
|
||
|
|
try {
|
||
|
|
const res = await fetch(`/api/tenants/${tenantId}`, { method: "DELETE" })
|
||
|
|
if (!res.ok) {
|
||
|
|
const data = await res.json().catch(() => null)
|
||
|
|
toast.error(data?.error ?? "Failed to delete tenant")
|
||
|
|
return
|
||
|
|
}
|
||
|
|
toast.success(`${tenantName ?? "Tenant"} deleted`)
|
||
|
|
if (refreshOnly) {
|
||
|
|
router.refresh()
|
||
|
|
} else {
|
||
|
|
router.push("/tenants")
|
||
|
|
router.refresh()
|
||
|
|
}
|
||
|
|
} catch {
|
||
|
|
toast.error("Network error — please try again")
|
||
|
|
} finally {
|
||
|
|
setLoading(false)
|
||
|
|
setOpen(false)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
return (
|
||
|
|
<>
|
||
|
|
{compact ? (
|
||
|
|
<button
|
||
|
|
onClick={(e) => { e.preventDefault(); e.stopPropagation(); setOpen(true) }}
|
||
|
|
className="text-white/20 hover:text-red-400 transition"
|
||
|
|
title="Delete tenant"
|
||
|
|
>
|
||
|
|
<Trash2 className="h-3.5 w-3.5" />
|
||
|
|
</button>
|
||
|
|
) : (
|
||
|
|
<button
|
||
|
|
onClick={() => setOpen(true)}
|
||
|
|
className="flex items-center gap-1.5 rounded-lg border border-red-500/20 px-3 py-2 text-sm text-red-400 hover:border-red-500/40 hover:bg-red-500/5 transition"
|
||
|
|
>
|
||
|
|
<Trash2 className="h-3.5 w-3.5" /> Delete
|
||
|
|
</button>
|
||
|
|
)}
|
||
|
|
|
||
|
|
<ConfirmModal
|
||
|
|
open={open}
|
||
|
|
title="Delete tenant?"
|
||
|
|
description={`Are you sure you want to delete ${tenantName ?? "this tenant"}? This frees their unit and cannot be undone.`}
|
||
|
|
confirmLabel="Delete"
|
||
|
|
loading={loading}
|
||
|
|
onConfirm={handleDelete}
|
||
|
|
onCancel={() => setOpen(false)}
|
||
|
|
/>
|
||
|
|
</>
|
||
|
|
)
|
||
|
|
}
|