import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { format } from "date-fns";
import {
	Edit,
	Eye,
	FileText,
	MoreHorizontal,
	PlusCircle,
	Search,
	Trash2,
} from "lucide-react";
import { useState } from "react";
import { Link } from "wouter";
import { DashboardLayout } from "@/components/layout/DashboardLayout";
import {
	AlertDialog,
	AlertDialogAction,
	AlertDialogCancel,
	AlertDialogContent,
	AlertDialogDescription,
	AlertDialogFooter,
	AlertDialogHeader,
	AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
	DropdownMenu,
	DropdownMenuContent,
	DropdownMenuItem,
	DropdownMenuSeparator,
	DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Skeleton } from "@/components/ui/skeleton";
import {
	Table,
	TableBody,
	TableCell,
	TableHead,
	TableHeader,
	TableRow,
} from "@/components/ui/table";
import { useAuth } from "@/hooks/use-auth";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import type { BlogPostListItem } from "@/lib/types";

export default function BlogManagement() {
	const { canManageContent } = useAuth();
	const [searchQuery, setSearchQuery] = useState("");
	const [postToDelete, setPostToDelete] = useState<string | null>(null);
	const queryClient = useQueryClient();
	const { toast } = useToast();

	// Fetch blog posts
	const { data: posts, isLoading } = useQuery<BlogPostListItem[]>({
		queryKey: ["/api/blog"],
	});

	// Delete mutation
	const deletePostMutation = useMutation({
		mutationFn: async (postId: string) => {
			return apiRequest("DELETE", `/api/blog/${postId}`);
		},
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ["/api/blog"] });
			toast({
				title: "Post deleted",
				description: "The blog post has been successfully deleted.",
			});
			setPostToDelete(null);
		},
		onError: (error) => {
			toast({
				title: "Error",
				description: "Failed to delete the blog post. Please try again.",
				variant: "destructive",
			});
			console.error("Delete error:", error);
		},
	});

	// Filter posts by search query
	const filteredPosts = posts?.filter(
		(post) =>
			post.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
			post.excerpt?.toLowerCase().includes(searchQuery.toLowerCase()),
	);

	return (
		<DashboardLayout title="Blog Management">
			<div className="mb-6 flex flex-col sm:flex-row justify-between gap-4">
				<div className="relative max-w-sm w-full">
					<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
					<Input
						type="search"
						placeholder="Search posts..."
						className="pl-8"
						value={searchQuery}
						onChange={(e) => setSearchQuery(e.target.value)}
					/>
				</div>

				<Link href="/dashboard/blog/create">
					<Button>
						<PlusCircle className="mr-2 h-4 w-4" />
						New Post
					</Button>
				</Link>
			</div>

			{/* Blog Posts Table */}
			<div className="rounded-md border">
				<Table>
					<TableHeader>
						<TableRow>
							<TableHead>Title</TableHead>
							<TableHead>Status</TableHead>
							<TableHead>Author</TableHead>
							<TableHead>Date</TableHead>
							<TableHead className="w-[100px]">Actions</TableHead>
						</TableRow>
					</TableHeader>
					<TableBody>
						{isLoading ? (
							Array.from({ length: 5 }).map((_, i) => (
								<TableRow key={i}>
									<TableCell>
										<Skeleton className="h-5 w-[250px]" />
									</TableCell>
									<TableCell>
										<Skeleton className="h-5 w-[80px]" />
									</TableCell>
									<TableCell>
										<Skeleton className="h-5 w-[120px]" />
									</TableCell>
									<TableCell>
										<Skeleton className="h-5 w-[100px]" />
									</TableCell>
									<TableCell>
										<Skeleton className="h-9 w-9 rounded-md" />
									</TableCell>
								</TableRow>
							))
						) : filteredPosts && filteredPosts.length > 0 ? (
							filteredPosts.map((post) => (
								<TableRow key={post.id}>
									<TableCell className="font-medium">{post.title}</TableCell>
									<TableCell>
										{post.publishedAt ? (
											<Badge
												variant="outline"
												className="bg-green-50 text-green-700 hover:bg-green-50 dark:bg-green-900/20 dark:text-green-400"
											>
												Published
											</Badge>
										) : (
											<Badge
												variant="outline"
												className="bg-orange-50 text-orange-700 hover:bg-orange-50 dark:bg-orange-900/20 dark:text-orange-400"
											>
												Draft
											</Badge>
										)}
									</TableCell>
									<TableCell>
										{post.author?.displayName || "Anonymous"}
									</TableCell>
									<TableCell>
										{post.publishedAt
											? format(new Date(post.publishedAt), "MMM d, yyyy")
											: format(new Date(post.createdAt), "MMM d, yyyy")}
									</TableCell>
									<TableCell>
										<DropdownMenu>
											<DropdownMenuTrigger asChild>
												<Button variant="ghost" className="h-8 w-8 p-0">
													<span className="sr-only">Open menu</span>
													<MoreHorizontal className="h-4 w-4" />
												</Button>
											</DropdownMenuTrigger>
											<DropdownMenuContent align="end">
												<DropdownMenuItem>
													<Link href={`/blog/${post.slug}`}>
														<span className="flex items-center">
															<Eye className="mr-2 h-4 w-4" />
															View
														</span>
													</Link>
												</DropdownMenuItem>

												<DropdownMenuItem>
													<Link href={`/dashboard/blog/edit/${post.id}`}>
														<span className="flex items-center">
															<Edit className="mr-2 h-4 w-4" />
															Edit
														</span>
													</Link>
												</DropdownMenuItem>

												{canManageContent && (
													<>
														<DropdownMenuSeparator />
														<DropdownMenuItem
															className="text-red-600 focus:text-red-600 dark:text-red-400 dark:focus:text-red-400"
															onClick={() => setPostToDelete(post.id)}
														>
															<Trash2 className="mr-2 h-4 w-4" />
															Delete
														</DropdownMenuItem>
													</>
												)}
											</DropdownMenuContent>
										</DropdownMenu>
									</TableCell>
								</TableRow>
							))
						) : (
							<TableRow>
								<TableCell colSpan={5} className="h-24 text-center">
									<div className="flex flex-col items-center justify-center text-muted-foreground">
										<FileText className="h-8 w-8 mb-2" />
										<p>No blog posts found</p>
										{searchQuery && (
											<p className="text-sm mt-1">
												Try adjusting your search query
											</p>
										)}
									</div>
								</TableCell>
							</TableRow>
						)}
					</TableBody>
				</Table>
			</div>

			{/* Delete Confirmation Dialog */}
			<AlertDialog
				open={!!postToDelete}
				onOpenChange={(open) => !open && setPostToDelete(null)}
			>
				<AlertDialogContent>
					<AlertDialogHeader>
						<AlertDialogTitle>Are you sure?</AlertDialogTitle>
						<AlertDialogDescription>
							This action cannot be undone. This will permanently delete the
							blog post and remove it from the platform.
						</AlertDialogDescription>
					</AlertDialogHeader>
					<AlertDialogFooter>
						<AlertDialogCancel>Cancel</AlertDialogCancel>
						<AlertDialogAction
							onClick={() => {
								if (postToDelete) {
									deletePostMutation.mutate(postToDelete);
								}
							}}
							className="bg-red-600 hover:bg-red-700 focus:ring-red-600"
						>
							Delete
						</AlertDialogAction>
					</AlertDialogFooter>
				</AlertDialogContent>
			</AlertDialog>
		</DashboardLayout>
	);
}
