import {useState, useEffect, useCallback} from "react";
import {AxiosError} from "axios";
import {useNavigate} from "react-router-dom";

import {getAllBlogsApi, deleteBlogApi} from "@/api/blog";

import {
	Table,
	TableBody,
	TableCell,
	TableHead,
	TableHeader,
	TableRow,
} from "@/components/ui/table";

import {Card, CardContent, CardHeader, CardTitle} from "@/components/ui/card";
import {Button} from "@/components/ui/button";
import {Input} from "@/components/ui/input";

import {Loader2, RefreshCw, Plus, Pencil, Trash} from "lucide-react";

interface Blog {
	id: number;
	title: string;
	writer: string;
	image: string | null;
}

export default function BlogPage() {
	const [blogs, setBlogs] = useState<Blog[]>([]);
	const [loading, setLoading] = useState(true);
	const [error, setError] = useState("");
	const [searchText, setSearchText] = useState("");

	const navigate = useNavigate();

	const fetchBlogs = useCallback(async () => {
		setLoading(true);
		setError("");

		try {
			const res = await getAllBlogsApi();

			if (Array.isArray(res)) {
				setBlogs(res);
			} else {
				setBlogs([]);
			}
		} catch (err) {
			if (err instanceof AxiosError) {
				setError(err.response?.data?.message || "Failed to load blogs");
			} else {
				setError("Something went wrong");
			}
		} finally {
			setLoading(false);
		}
	}, []);

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

	const filteredBlogs = blogs.filter((b) => {
		const text = searchText.toLowerCase();

		return (
			b.title?.toLowerCase().includes(text) ||
			b.writer?.toLowerCase().includes(text)
		);
	});

	async function handleDelete(id: number) {
		const confirmDelete = confirm("Delete this blog?");
		if (!confirmDelete) return;

		try {
			await deleteBlogApi(id);
			fetchBlogs();
		} catch (error) {
			console.error(error);
		}
	}

	return (
		<div className="p-6 space-y-6">
			<div className="flex flex-col md:flex-row md:justify-between md:items-center gap-3">
				<h1 className="text-2xl font-bold">Blogs</h1>

				<div className="flex flex-wrap gap-3">
					<Input
						placeholder="Search blog..."
						value={searchText}
						onChange={(e) => setSearchText(e.target.value)}
						className="w-[220px]"
					/>

					<Button variant="outline" onClick={fetchBlogs} disabled={loading}>
						<RefreshCw className="mr-2 h-4 w-4" />
						Refresh
					</Button>

					<Button onClick={() => navigate("/blog/create")}>
						<Plus className="mr-2 h-4 w-4" />
						Add Blog
					</Button>
				</div>
			</div>

			{error && (
				<div className="p-4 text-red-600 bg-red-50 border rounded-md">
					{error}
				</div>
			)}

			<Card>
				<CardHeader>
					<CardTitle>Blog List</CardTitle>
				</CardHeader>

				<CardContent>
					<div className="border rounded-md overflow-x-auto max-w-full">
						<Table>
							<TableHeader>
								<TableRow>
									<TableHead>ID</TableHead>
									<TableHead>Title</TableHead>
									<TableHead>Writer</TableHead>
									<TableHead>Actions</TableHead>
								</TableRow>
							</TableHeader>

							<TableBody>
								{loading ? (
									<TableRow>
										<TableCell colSpan={4} className="text-center">
											<Loader2 className="h-6 w-6 animate-spin mx-auto" />
										</TableCell>
									</TableRow>
								) : filteredBlogs.length === 0 ? (
									<TableRow>
										<TableCell colSpan={4} className="text-center">
											No blogs found
										</TableCell>
									</TableRow>
								) : (
									filteredBlogs.map((blog) => (
										<TableRow key={blog.id}>
											<TableCell>{blog.id}</TableCell>

											<TableCell>{blog.title}</TableCell>

											<TableCell>{blog.writer}</TableCell>

											<TableCell className="flex gap-2">
												<Button
													size="sm"
													variant="outline"
													onClick={() => navigate(`/blog/edit/${blog.id}`)}
												>
													<Pencil className="h-4 w-4" />
												</Button>

												<Button
													size="sm"
													variant="destructive"
													onClick={() => handleDelete(blog.id)}
												>
													<Trash className="h-4 w-4" />
												</Button>
											</TableCell>
										</TableRow>
									))
								)}
							</TableBody>
						</Table>
					</div>
				</CardContent>
			</Card>
		</div>
	);
}
