"use client";

import { Eye, Heart, MoreHorizontal, Share2 } from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import * as React from "react";
import { toast } from "sonner";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
	Card,
	CardContent,
	CardFooter,
	CardHeader,
} from "@/components/ui/card";
import { useAuth } from "@/providers/auth-provider";
import { ContentService } from "@/services/content.service";
import { FavoriteService } from "@/services/favorite.service";
import type { Content } from "@/types/content";

interface ContentCardProps {
	content: Content;
}

export function ContentCard({ content }: ContentCardProps) {
	const { isAuthenticated } = useAuth();
	const router = useRouter();
	const [isLiked, setIsLiked] = React.useState(content.isLiked || false);
	const [likesCount, setLikesCount] = React.useState(content.favoritesCount);

	React.useEffect(() => {
		setIsLiked(content.isLiked || false);
		setLikesCount(content.favoritesCount);
	}, [content.isLiked, content.favoritesCount]);

	const handleLike = async (e: React.MouseEvent) => {
		e.preventDefault();
		e.stopPropagation();

		if (!isAuthenticated) {
			toast.error("Vous devez être connecté pour liker un mème");
			router.push("/login");
			return;
		}

		try {
			if (isLiked) {
				await FavoriteService.remove(content.id);
				setIsLiked(false);
				setLikesCount((prev) => prev - 1);
			} else {
				await FavoriteService.add(content.id);
				setIsLiked(true);
				setLikesCount((prev) => prev + 1);
			}
		} catch (_error) {
			toast.error("Une erreur est survenue");
		}
	};

	const handleUse = async (e: React.MouseEvent) => {
		e.preventDefault();
		e.stopPropagation();
		try {
			await ContentService.incrementUsage(content.id);
			toast.success("Mème prêt à être utilisé !");
		} catch (_error) {
			toast.error("Une erreur est survenue");
		}
	};

	return (
		<Card className="overflow-hidden border-none shadow-sm hover:shadow-md transition-shadow">
			<CardHeader className="p-4 flex flex-row items-center space-y-0 gap-3">
				<Avatar className="h-8 w-8">
					<AvatarImage src={content.author.avatarUrl} />
					<AvatarFallback>{content.author.username[0].toUpperCase()}</AvatarFallback>
				</Avatar>
				<div className="flex flex-col">
					<Link
						href={`/user/${content.author.username}`}
						className="text-sm font-semibold hover:underline"
					>
						{content.author.displayName || content.author.username}
					</Link>
					<span className="text-xs text-muted-foreground">
						{new Date(content.createdAt).toLocaleDateString("fr-FR")}
					</span>
				</div>
				<Button variant="ghost" size="icon" className="ml-auto h-8 w-8">
					<MoreHorizontal className="h-4 w-4" />
				</Button>
			</CardHeader>
			<CardContent className="p-0 relative bg-zinc-100 dark:bg-zinc-900 aspect-square flex items-center justify-center">
				<Link href={`/meme/${content.slug}`} className="w-full h-full relative">
					{content.type === "image" ? (
						<Image
							src={content.url}
							alt={content.title}
							fill
							className="object-contain"
							sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
						/>
					) : (
						<video
							src={content.url}
							controls={false}
							autoPlay
							muted
							loop
							className="w-full h-full object-contain"
						/>
					)}
				</Link>
			</CardContent>
			<CardFooter className="p-4 flex flex-col gap-4">
				<div className="w-full flex items-center justify-between">
					<div className="flex items-center gap-2">
						<Button
							variant="ghost"
							size="sm"
							className={`gap-1.5 h-8 ${isLiked ? "text-red-500 hover:text-red-600" : ""}`}
							onClick={handleLike}
						>
							<Heart className={`h-4 w-4 ${isLiked ? "fill-current" : ""}`} />
							<span className="text-xs">{likesCount}</span>
						</Button>
						<Button variant="ghost" size="sm" className="gap-1.5 h-8">
							<Eye className="h-4 w-4" />
							<span className="text-xs">{content.views}</span>
						</Button>
						<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
							<Share2 className="h-4 w-4" />
						</Button>
					</div>
					<Button
						size="sm"
						variant="secondary"
						className="text-xs h-8"
						onClick={handleUse}
					>
						Utiliser
					</Button>
				</div>

				<div className="w-full space-y-2">
					<h3 className="font-medium text-sm line-clamp-2">{content.title}</h3>
					<div className="flex flex-wrap gap-1">
						{content.tags.slice(0, 3).map((tag, _i) => (
							<Badge
								key={typeof tag === "string" ? tag : tag.id}
								variant="secondary"
								className="text-[10px] py-0 px-1.5"
							>
								#{typeof tag === "string" ? tag : tag.name}
							</Badge>
						))}
					</div>
				</div>
			</CardFooter>
		</Card>
	);
}
