import { useState, useEffect, useCallback } from "react";

import {
	getNewsApi,
	createNewsApi,
	updateNewsApi,
	deleteNewsApi,
} from "@/api/newsMedia";

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 {
	Dialog,
	DialogContent,
	DialogHeader,
	DialogTitle,
	DialogFooter,
} from "@/components/ui/dialog";

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

export default function NewsPage() {
	const [news, setNews] = useState<any[]>([]);
	const [loading, setLoading] = useState(true);

	const [searchText, setSearchText] = useState("");

	const [openModal, setOpenModal] = useState(false);
	const [editing, setEditing] = useState<any>(null);

	const [viewOpen, setViewOpen] = useState(false);
	const [viewData, setViewData] = useState<any>(null);

	const [currentPage, setCurrentPage] = useState(1);
	const [itemsPerPage, setItemsPerPage] = useState(10);

	const [form, setForm] = useState({
		headline: "",
		content: "",
		firstPara: "",
		secondPara: "",
		date: "",
		author: "",
	});

	const fetchAll = useCallback(async () => {
		setLoading(true);
		try {
			const res = await getNewsApi();
			setNews(res?.data || []);
		} catch (err) {
			console.error(err);
		} finally {
			setLoading(false);
		}
	}, []);

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

	const filteredNews = news.filter((item) =>
		item.Headline?.toLowerCase().includes(searchText.toLowerCase()),
	);

	const totalPages = Math.ceil(filteredNews.length / itemsPerPage);
	const startIndex = (currentPage - 1) * itemsPerPage;
	const paginatedData = filteredNews.slice(
		startIndex,
		startIndex + itemsPerPage,
	);

	function handleChange(e: any) {
		setForm({ ...form, [e.target.name]: e.target.value });
	}

	function openAdd() {
		setEditing(null);
		setForm({
			headline: "",
			content: "",
			firstPara: "",
			secondPara: "",
			date: "",
			author: "",
		});
		setOpenModal(true);
	}

	function openEdit(item: any) {
		setEditing(item);

		setForm({
			headline: item.Headline || "",
			content: item.Content || "",
			firstPara: item.FirstPara || "",
			secondPara: item.SecondPara || "",
			date: item.Date ? item.Date.split("T")[0] : "",
			author: item.Author || "",
		});

		setOpenModal(true);
	}

	function openView(item: any) {
		setViewData(item);
		setViewOpen(true);
	}

	async function handleSubmit() {
		try {
			if (editing) {
				await updateNewsApi(editing.Id, form);
			} else {
				await createNewsApi(form);
			}
			setOpenModal(false);
			fetchAll();
		} catch (err) {
			console.error(err);
		}
	}

	async function handleDelete(id: number) {
		if (!confirm("Delete news?")) return;
		await deleteNewsApi(id);
		fetchAll();
	}

	return (
		<div className="p-6 space-y-6">
			<div className="flex justify-between items-center flex-wrap gap-3">
				<h1 className="text-2xl font-bold">News Media</h1>

				<div className="flex gap-2 flex-wrap items-center">
					<Input
						placeholder="Search headline..."
						value={searchText}
						onChange={(e) => {
							setSearchText(e.target.value);
							setCurrentPage(1);
						}}
						className="w-[250px]"
					/>

					<select
						value={itemsPerPage}
						onChange={(e) => {
							setItemsPerPage(Number(e.target.value));
							setCurrentPage(1);
						}}
						className="border px-2 py-1 rounded">
						<option value={5}>5 / page</option>
						<option value={10}>10 / page</option>
						<option value={20}>20 / page</option>
					</select>

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

					<Button onClick={openAdd}>
						<Plus className="mr-2 h-4 w-4" />
						Add News
					</Button>
				</div>
			</div>

			<Card>
				<CardHeader>
					<CardTitle>News List</CardTitle>
				</CardHeader>

				<CardContent>
					<div className="overflow-x-auto">
						<Table className="min-w-[900px] table-fixed">
							<TableHeader>
								<TableRow>
									<TableHead className="w-[60px]">ID</TableHead>
									<TableHead className="w-[220px]">Headline</TableHead>
									<TableHead className="w-[120px]">Author</TableHead>
									<TableHead className="w-[120px]">Date</TableHead>
									<TableHead className="w-[260px]">Content</TableHead>
									<TableHead className="w-[150px]">Actions</TableHead>
								</TableRow>
							</TableHeader>

							<TableBody>
								{loading ? (
									<TableRow>
										<TableCell colSpan={6} className="text-center">
											<Loader2 className="animate-spin mx-auto" />
										</TableCell>
									</TableRow>
								) : paginatedData.length === 0 ? (
									<TableRow>
										<TableCell colSpan={6} className="text-center">
											No news found
										</TableCell>
									</TableRow>
								) : (
									paginatedData.map((item) => (
										<TableRow key={item.Id}>
											<TableCell>{item.Id}</TableCell>

											<TableCell className="break-words whitespace-normal">
												{item.Headline}
											</TableCell>

											<TableCell>{item.Author}</TableCell>

											<TableCell>
												{item.Date
													? new Date(item.Date).toLocaleDateString()
													: "-"}
											</TableCell>

											<TableCell className="break-words whitespace-normal">
												{item.Content}
											</TableCell>

											<TableCell className="flex gap-2">
												<Button
													size="sm"
													variant="outline"
													onClick={() => openView(item)}>
													<Eye className="h-4 w-4" />
												</Button>

												<Button
													size="sm"
													variant="outline"
													onClick={() => openEdit(item)}>
													<Pencil className="h-4 w-4" />
												</Button>

												<Button
													size="sm"
													variant="destructive"
													onClick={() => handleDelete(Number(item.Id))}>
													<Trash className="h-4 w-4" />
												</Button>
											</TableCell>
										</TableRow>
									))
								)}
							</TableBody>
						</Table>
					</div>

					{/* PAGINATION */}
					<div className="flex justify-between items-center mt-4">
						<p className="text-sm">
							Page {currentPage} of {totalPages}
						</p>

						<div className="flex gap-2">
							<Button
								variant="outline"
								size="sm"
								disabled={currentPage === 1}
								onClick={() => setCurrentPage((p) => p - 1)}>
								<ChevronLeft className="h-4 w-4" />
							</Button>

							<Button
								variant="outline"
								size="sm"
								disabled={currentPage === totalPages}
								onClick={() => setCurrentPage((p) => p + 1)}>
								<ChevronRight className="h-4 w-4" />
							</Button>
						</div>
					</div>
				</CardContent>
			</Card>

			{/* CREATE / EDIT MODAL */}
			<Dialog open={openModal} onOpenChange={setOpenModal}>
				<DialogContent className="w-[95vw] max-w-none max-h-[90vh] overflow-y-auto">
					<DialogHeader>
						<DialogTitle>{editing ? "Edit News" : "Add News"}</DialogTitle>
					</DialogHeader>

					<div className="space-y-3">
						<Input
							name="headline"
							placeholder="Headline"
							value={form.headline}
							onChange={handleChange}
						/>
						<Input
							name="author"
							placeholder="Author"
							value={form.author}
							onChange={handleChange}
						/>
						<Input
							type="date"
							name="date"
							value={form.date}
							onChange={handleChange}
						/>

						<textarea
							name="firstPara"
							placeholder="First Paragraph"
							value={form.firstPara}
							onChange={handleChange}
							className="border rounded p-2 w-full min-h-[100px]"
						/>
						<textarea
							name="secondPara"
							placeholder="Second Paragraph"
							value={form.secondPara}
							onChange={handleChange}
							className="border rounded p-2 w-full min-h-[100px]"
						/>
						<textarea
							name="content"
							placeholder="Content"
							value={form.content}
							onChange={handleChange}
							className="border rounded p-2 w-full min-h-[150px]"
						/>
					</div>

					<DialogFooter>
						<Button variant="outline" onClick={() => setOpenModal(false)}>
							Cancel
						</Button>
						<Button onClick={handleSubmit}>
							{editing ? "Update" : "Create"}
						</Button>
					</DialogFooter>
				</DialogContent>
			</Dialog>

			{/* VIEW MODAL */}
			<Dialog open={viewOpen} onOpenChange={setViewOpen}>
				<DialogContent className="w-[95vw] max-w-none max-h-[90vh] overflow-y-auto p-6">
					<DialogHeader>
						<DialogTitle>News Details</DialogTitle>
					</DialogHeader>

					{viewData && (
						<div className="space-y-4 text-sm">
							<b>Headline:</b>
							<p>{viewData.Headline}</p>

							<b>Author:</b>
							<p>{viewData.Author}</p>

							<b>Date:</b>
							<p>
								{viewData.Date
									? new Date(viewData.Date).toLocaleDateString()
									: "-"}
							</p>

							<b>First Para:</b>
							<p className="whitespace-pre-line">{viewData.FirstPara}</p>

							<b>Second Para:</b>
							<p className="whitespace-pre-line">{viewData.SecondPara}</p>

							<b>Content:</b>
							<p className="whitespace-pre-line">{viewData.Content}</p>
						</div>
					)}

					<DialogFooter>
						<Button onClick={() => setViewOpen(false)}>Close</Button>
					</DialogFooter>
				</DialogContent>
			</Dialog>
		</div>
	);
}
