"use client";

import {
	AlertDialog,
	AlertDialogTrigger,
	AlertDialogCancel,
	AlertDialogContent,
	AlertDialogDescription,
	AlertDialogFooter,
	AlertDialogHeader,
	AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Trash2 } from "lucide-react";
import hasPermissions from "@/lib/hasPermissions";
import IUser from "@/interfaces/IUser";
import request from "@/lib/request";

interface DeleteArticleButtonProps {
	id: string;
	user?: IUser;
}

const DeleteArticleButton: React.FC<DeleteArticleButtonProps> = ({
	id,
	user,
}) => {
	const perms =
		user && hasPermissions(user.roles, { blogs: ["delete"] } as const);
	if (!perms?.blogs.delete) {
		return null;
	}

	const handleDelete = async (e: React.MouseEvent) => {
		e.preventDefault();
		await request(`/blogs/${id}/delete`, {
			requiresAuth: true,
			method: "DELETE",
		});
		// 	if (res.status === "Success") {
		// 		toast({
		// 			title: "Article supprimé",
		// 			description: "L'article a été supprimé avec succès.",
		// 		});
		// 		setOpen(false); // Only close on success
		// 		router.replace("/blogs");
		// 	} else {
		// 		toast({
		// 			title: "Erreur",
		// 			description: res?.message || "Une erreur est survenue.",
		// 			variant: "destructive",
		// 		});
		// 		// Don't setOpen(false) here - keep dialog open on error
		// 	}
		// } catch (e: unknown) {
		// 	toast({
		// 		title: "Erreur",
		// 		description:
		// 			(e as Error)?.message || "Une erreur est survenue.",
		// 		variant: "destructive",
		// 	});
		// 	// Don't setOpen(false) here - keep dialog open on exception
		// } finally {
		// 	setIsDeleting(false); // Just reset the loading state
		// }
	};

	return (
		<AlertDialog>
			<AlertDialogTrigger asChild>
				<Button variant="destructive">
					<Trash2 className="h-4 w-4" />
				</Button>
			</AlertDialogTrigger>
			<AlertDialogContent>
				<AlertDialogHeader>
					<AlertDialogTitle>
						Êtes-vous sûr de vouloir supprimer cet article ?
					</AlertDialogTitle>
					<AlertDialogDescription>
						Cette action supprimera définitivement cet article.
					</AlertDialogDescription>
				</AlertDialogHeader>
				<AlertDialogFooter>
					<AlertDialogCancel>Annuler</AlertDialogCancel>
					<Button variant="destructive" onClick={handleDelete}>
						Supprimer
					</Button>
				</AlertDialogFooter>
			</AlertDialogContent>
		</AlertDialog>
	);
};

export default DeleteArticleButton;
