import Image from "next/image";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { CalendarIcon } from "lucide-react";
import { Blog } from "@/types/types";
import IUser from "@/interfaces/IUser";
import hasPermissions from "@/lib/hasPermissions";
import { Button } from "./ui/button";
import DeleteArticleButton from "./article/delete-button";
import Link from "next/link";

const BlogArticle: React.FC<{ blog: Blog; user?: IUser }> = ({
	blog,
	user,
}) => {
	const UpdateButton = () => {
		if (!user || !hasPermissions(user.roles, { blogs: ["update"] })) return;

		return (
			<Button variant="secondary">
				<Link href={`/dashboard/blogs/${blog.blogID}`}>Modifier</Link>
			</Button>
		);
	};

	return (
		<article className="mx-auto max-w-3xl px-4 py-8 md:py-12">
			<div className="space-y-6">
				<div className="space-y-2">
					<div className="flex items-center gap-2">
						{blog.category && (
							<Badge variant="secondary">{blog.category}</Badge>
						)}
						<time className="flex items-center text-sm text-muted-foreground">
							<CalendarIcon className="mr-1 h-4 w-4" />
							{new Date(blog.published).toLocaleString()}
						</time>
					</div>
					<h1 className="text-3xl font-bold tracking-tight sm:text-4xl">
						{blog.title}
					</h1>
					{blog.summary && (
						<p className="text-lg text-muted-foreground">
							{blog.summary}
						</p>
					)}
				</div>

				<div className="flex justify-between">
					<div className="flex items-center gap-3">
						<Avatar>
							<AvatarImage
								src={`https://avatar.vercel.sh/blog.author.userId`}
								alt={`${blog.author.firstname} ${blog.author.lastname}`}
							/>
							<AvatarFallback>
								{(
									blog.author.firstname[0] +
									blog.author.lastname[0]
								).toUpperCase()}
							</AvatarFallback>
						</Avatar>
						<div>
							<p className="font-medium">
								{blog.author.firstname} {blog.author.lastname}
							</p>
							<p className="text-sm text-muted-foreground">idk</p>
						</div>
					</div>
					<div className="flex gap-2">
						<UpdateButton />
						<DeleteArticleButton id={blog.blogID} user={user} />
					</div>
				</div>

				<div className="relative aspect-video overflow-hidden rounded-lg">
					<img
						src={blog.image ?? "/placeholder.svg"}
						alt={blog.title}
						className="object-contain"
					/>
				</div>

				<div
					className="prose prose-lg prose-slate dark:prose-invert"
					dangerouslySetInnerHTML={{ __html: blog.content }}
				/>
			</div>
		</article>
	);
};

export default BlogArticle;
