"use client";

import { useState, useTransition } from "react";
import { toast } from "sonner";
import { Trash2, Loader2 } from "lucide-react";
import { deleteRole } from "../actions";
import { Button } from "@/components/ui/button";
import {
  AlertDialog,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import type { Role } from "@/lib/types";

export function DeleteRoleButton({ role }: { role: Role }) {
  const [open, setOpen] = useState(false);
  const [pending, startTransition] = useTransition();

  if (role.is_system) {
    return (
      <Button
        variant="outline"
        size="sm"
        disabled
        className="opacity-50 cursor-not-allowed text-muted-foreground"
        title="System roles cannot be deleted"
      >
        <Trash2 className="mr-1.5 size-4" />
        Delete
      </Button>
    );
  }

  function onDelete() {
    startTransition(async () => {
      const res = await deleteRole(role.id);
      if (res?.ok) {
        toast.success(`Role "${role.name}" deleted successfully`);
        setOpen(false);
      } else if (res?.error) {
        toast.error(res.error);
      }
    });
  }

  return (
    <AlertDialog open={open} onOpenChange={setOpen}>
      <AlertDialogTrigger asChild>
        <Button
          variant="outline"
          size="sm"
          className="text-destructive hover:bg-destructive/10 hover:text-destructive"
        >
          <Trash2 className="mr-1.5 size-4" />
          Delete
        </Button>
      </AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Are you sure you want to delete this role?</AlertDialogTitle>
          <AlertDialogDescription>
            This will permanently delete the custom role{" "}
            <strong className="text-foreground">{role.name}</strong> and remove all associated role permissions. This action cannot be undone.
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel disabled={pending}>Cancel</AlertDialogCancel>
          <Button
            variant="destructive"
            onClick={onDelete}
            disabled={pending}
          >
            {pending ? (
              <>
                <Loader2 className="mr-2 size-4 animate-spin" />
                Deleting…
              </>
            ) : (
              "Delete Role"
            )}
          </Button>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}
