"use client";

import { format } from "date-fns";
import { fr } from "date-fns/locale";
import {
	Download,
	Edit,
	Eye,
	Image as ImageIcon,
	MoreHorizontal,
	Trash2,
	Video,
} from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
	DropdownMenu,
	DropdownMenuContent,
	DropdownMenuItem,
	DropdownMenuLabel,
	DropdownMenuSeparator,
	DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Skeleton } from "@/components/ui/skeleton";
import {
	Table,
	TableBody,
	TableCell,
	TableHead,
	TableHeader,
	TableRow,
} from "@/components/ui/table";
import { ContentService } from "@/services/content.service";
import type { Content } from "@/types/content";
import { ContentEditDialog } from "./content-edit-dialog";

export default function AdminContentsPage() {
	const [contents, setContents] = useState<Content[]>([]);
	const [loading, setLoading] = useState(true);
	const [totalCount, setTotalCount] = useState(0);
	const [selectedContent, setSelectedContent] = useState<Content | null>(null);
	const [dialogOpen, setDialogOpen] = useState(false);

	const fetchContents = useCallback(() => {
		setLoading(true);
		ContentService.getExplore({ limit: 20 })
			.then((res) => {
				setContents(res.data);
				setTotalCount(res.totalCount);
			})
			.catch((err) => console.error(err))
			.finally(() => setLoading(false));
	}, []);

	useEffect(() => {
		fetchContents();
	}, [fetchContents]);

	const handleDelete = async (id: string) => {
		if (!confirm("Êtes-vous sûr de vouloir supprimer ce contenu ?")) return;

		try {
			await ContentService.removeAdmin(id);
			setContents(contents.filter((c) => c.id !== id));
			setTotalCount((prev) => prev - 1);
		} catch (error) {
			console.error(error);
		}
	};

	const handleEdit = (content: Content) => {
		setSelectedContent(content);
		setDialogOpen(true);
	};

	return (
		<div className="flex-1 space-y-4 p-4 pt-6 md:p-8">
			<div className="flex items-center justify-between">
				<h2 className="text-3xl font-bold tracking-tight">
					Contenus ({totalCount})
				</h2>
			</div>
			<div className="rounded-md border bg-card">
				<Table>
					<TableHeader>
						<TableRow>
							<TableHead>Contenu</TableHead>
							<TableHead className="hidden sm:table-cell">Catégorie</TableHead>
							<TableHead className="hidden md:table-cell">Auteur</TableHead>
							<TableHead className="hidden lg:table-cell">Stats</TableHead>
							<TableHead className="hidden xl:table-cell">Date</TableHead>
							<TableHead className="w-[100px]"></TableHead>
						</TableRow>
					</TableHeader>
					<TableBody>
						{loading ? (
							Array.from({ length: 5 }).map((_, i) => (
								/* biome-ignore lint/suspicious/noArrayIndexKey: skeleton items don't have unique IDs */
								<TableRow key={i}>
									<TableCell>
										<Skeleton className="h-10 w-[200px]" />
									</TableCell>
									<TableCell className="hidden sm:table-cell">
										<Skeleton className="h-4 w-[100px]" />
									</TableCell>
									<TableCell className="hidden md:table-cell">
										<Skeleton className="h-4 w-[100px]" />
									</TableCell>
									<TableCell className="hidden lg:table-cell">
										<Skeleton className="h-4 w-[80px]" />
									</TableCell>
									<TableCell className="hidden xl:table-cell">
										<Skeleton className="h-4 w-[100px]" />
									</TableCell>
									<TableCell>
										<Skeleton className="h-8 w-8 rounded-full" />
									</TableCell>
								</TableRow>
							))
						) : contents.length === 0 ? (
							<TableRow>
								<TableCell colSpan={6} className="text-center h-24">
									Aucun contenu trouvé.
								</TableCell>
							</TableRow>
						) : (
							contents.map((content) => (
								<TableRow key={content.id}>
									<TableCell className="font-medium">
										<div className="flex items-center gap-3">
											<div className="flex h-10 w-10 items-center justify-center rounded bg-muted">
												{content.mimeType.startsWith("image/") ? (
													<ImageIcon className="h-5 w-5 text-muted-foreground" />
												) : (
													<Video className="h-5 w-5 text-muted-foreground" />
												)}
											</div>
											<div>
												<div className="font-semibold">{content.title}</div>
												<div className="text-xs text-muted-foreground">
													{content.type} • {content.mimeType}
												</div>
											</div>
										</div>
									</TableCell>
									<TableCell className="hidden sm:table-cell">
										<Badge variant="outline">
											{content.category?.name || "Sans catégorie"}
										</Badge>
									</TableCell>
									<TableCell className="hidden md:table-cell">
										@{content.author.username}
									</TableCell>
									<TableCell className="hidden lg:table-cell">
										<div className="flex flex-col gap-1 text-xs">
											<div className="flex items-center gap-1">
												<Eye className="h-3 w-3" /> {content.views}
											</div>
											<div className="flex items-center gap-1">
												<Download className="h-3 w-3" /> {content.usageCount}
											</div>
										</div>
									</TableCell>
									<TableCell className="hidden xl:table-cell whitespace-nowrap">
										{format(new Date(content.createdAt), "dd/MM/yyyy", { locale: fr })}
									</TableCell>
									<TableCell>
										<DropdownMenu>
											<DropdownMenuTrigger asChild>
												<Button variant="ghost" size="icon">
													<MoreHorizontal className="h-4 w-4" />
													<span className="sr-only">Actions</span>
												</Button>
											</DropdownMenuTrigger>
											<DropdownMenuContent align="end">
												<DropdownMenuLabel>Actions</DropdownMenuLabel>
												<DropdownMenuSeparator />
												<DropdownMenuItem onClick={() => handleEdit(content)}>
													<Edit className="mr-2 h-4 w-4" /> Modifier
												</DropdownMenuItem>
												<DropdownMenuItem
													onClick={() => handleDelete(content.id)}
													className="text-destructive focus:text-destructive"
												>
													<Trash2 className="mr-2 h-4 w-4" /> Supprimer
												</DropdownMenuItem>
											</DropdownMenuContent>
										</DropdownMenu>
									</TableCell>
								</TableRow>
							))
						)}
					</TableBody>
				</Table>
			</div>
			<ContentEditDialog
				content={selectedContent}
				open={dialogOpen}
				onOpenChange={setDialogOpen}
				onSuccess={fetchContents}
			/>
		</div>
	);
}
