"use client";

import * as React from "react";
import { format } from "date-fns";
import { CircleX, Edit, MoreHorizontal, Trash } from "lucide-react";
import Link from "next/link";

import { Button } from "@/components/ui/button";
import {
	Dialog,
	DialogContent,
	DialogDescription,
	DialogHeader,
	DialogTitle,
} from "@/components/ui/dialog";
import {
	DropdownMenu,
	DropdownMenuContent,
	DropdownMenuItem,
	DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
	Select,
	SelectContent,
	SelectItem,
	SelectTrigger,
	SelectValue,
} from "@/components/ui/select";
import {
	Table,
	TableBody,
	TableCell,
	TableHead,
	TableHeader,
	TableRow,
} from "@/components/ui/table";
import { Blog, Category } from "@/types/types";
import { useApi } from "@/hooks/use-api";
import request from "@/lib/request";
import IUser from "@/interfaces/IUser";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useCallback } from "react";
import hasPermissions from "@/lib/hasPermissions";

export default function BlogTable({ user }: { user: IUser }) {
	const searchParams = useSearchParams();
	const pathname = usePathname(); // Get current path

	const { replace } = useRouter();

	const canUpdate = hasPermissions(user.roles, { blogs: ["update"] });
	const canInsert = hasPermissions(user.roles, { blogs: ["insert"] });
	const canDelete = hasPermissions(user.roles, { blogs: ["delete"] });

	const updateSearchParam = useCallback(
		(key: string, value?: string) => {
			const params = new URLSearchParams(searchParams);
			if (value) {
				params.set(key, value);
			} else {
				params.delete(key);
			}
			replace(`${pathname}?${params.toString()}`);
		},
		[searchParams, pathname, replace],
	);

	let url = "/blogs";
	const category = searchParams.get("category");
	if (category) url += `?category=${category}`;

	const blogs = useApi<Blog[]>(url, {}, false, false);

	const categories = useApi<Category[]>(
		"/blogs/categories",
		{},
		false,
		false,
	);

	const [deleteDialogOpen, setDeleteDialogOpen] = React.useState(false);
	const [blogToDelete, setBlogToDelete] = React.useState<Blog | null>(null);

	const handleDelete = async (blog: Blog) => {
		setBlogToDelete(blog);
		setDeleteDialogOpen(true);
	};

	const confirmDelete = async () => {
		if (!blogToDelete) return;

		try {
			const res = await request(`/blogs/${blogToDelete.blogID}/delete`, {
				method: "DELETE",
				requiresAuth: true,
			});

			if (res.status === "Success") {
				blogs.mutate();
			}

			setDeleteDialogOpen(false);
			setBlogToDelete(null);
		} catch (error) {
			console.error("Failed to delete blog:", error);
		}
	};

	return (
		<div className="flex flex-col gap-4 m-4">
			<div className="flex items-center justify-between gap-4">
				<div className="flex gap-4">
					<Select
						value={category || ""}
						onValueChange={(v) => {
							updateSearchParam("category", v);
						}}
					>
						<SelectTrigger className="w-[180px]">
							<SelectValue placeholder="Catégories" />
						</SelectTrigger>
						<SelectContent>
							{categories.data?.map((c) => (
								<SelectItem key={c.category} value={c.category}>
									{c.category} ({c.count})
								</SelectItem>
							))}
						</SelectContent>
					</Select>
					{category && (
						<Button
							onClick={() => updateSearchParam("category")}
							variant="destructive"
						>
							<CircleX />
						</Button>
					)}
				</div>
				{canInsert && (
					<Button asChild>
						<Link href="/dashboard/blogs/new">Nouvel article</Link>
					</Button>
				)}
			</div>

			<div className="rounded-md border">
				<Table>
					<TableHeader>
						<TableRow>
							<TableHead>Titre</TableHead>
							<TableHead>Catégorie</TableHead>
							<TableHead>Auteur</TableHead>
							<TableHead>Publié</TableHead>
							{(canUpdate || canDelete) && (
								<TableHead className="w-[100px]">
									Actions
								</TableHead>
							)}
						</TableRow>
					</TableHeader>
					<TableBody>
						{blogs.data?.map((blog) => (
							<TableRow key={blog.blogID}>
								<TableCell className="font-medium">
									{blog.title}
								</TableCell>
								<TableCell>{blog.category}</TableCell>
								<TableCell>
									{blog.author.firstname}{" "}
									{blog.author.lastname}
								</TableCell>
								<TableCell>
									{format(
										new Date(blog.published),
										"MMM d, yyyy",
									)}
								</TableCell>
								{(canDelete || canUpdate) && (
									<TableCell>
										<DropdownMenu>
											<DropdownMenuTrigger asChild>
												<Button
													variant="ghost"
													size="icon"
												>
													<MoreHorizontal className="h-4 w-4" />
													<span className="sr-only">
														Ouvrir le menu
													</span>
												</Button>
											</DropdownMenuTrigger>
											<DropdownMenuContent align="end">
												{canUpdate && (
													<DropdownMenuItem asChild>
														<Link
															href={`/dashboard/blogs/${blog.blogID}`}
															className="flex items-center"
														>
															<Edit className="mr-2 h-4 w-4" />
															Modifier
														</Link>
													</DropdownMenuItem>
												)}
												{canDelete && (
													<DropdownMenuItem
														className="flex items-center text-destructive focus:text-destructive"
														onClick={() =>
															handleDelete(blog)
														}
													>
														<Trash className="mr-2 h-4 w-4" />
														Supprimer
													</DropdownMenuItem>
												)}
											</DropdownMenuContent>
										</DropdownMenu>
									</TableCell>
								)}
							</TableRow>
						))}
					</TableBody>
				</Table>
			</div>

			<Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
				<DialogContent>
					<DialogHeader>
						<DialogTitle>Êtes-vous sûr ?</DialogTitle>
						<DialogDescription>
							Cela supprimera définitivement l'article{" "}
							<span className="font-medium">
								{blogToDelete?.title}
							</span>
							.
						</DialogDescription>
					</DialogHeader>
					<div className="flex justify-end gap-3">
						<Button
							variant="outline"
							onClick={() => setDeleteDialogOpen(false)}
						>
							Annuler
						</Button>
						<Button variant="destructive" onClick={confirmDelete}>
							Supprimer
						</Button>
					</div>
				</DialogContent>
			</Dialog>
		</div>
	);
}
