import { useState, useEffect, useCallback } from "react";
import { BytescaleUploader } from "@/components/BytescaleUploader/BytescaleUploader";

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 { Textarea } from "@/components/ui/textarea";

import {
	Dialog,
	DialogContent,
	DialogHeader,
	DialogTitle,
	DialogFooter,
} from "@/components/ui/dialog";

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

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

	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: "",
		imageUrls: [] as string[],
		firstPara: "",
		secondPara: "",
		date: "",
		author: "",
	});

	const fetchAll = useCallback(async () => {
		setLoading(true);
		try {
			const res = await getNewsApi(currentPage, itemsPerPage, searchText);

			setNews(res?.data || []);
			setTotalItems(res?.meta?.total || 0);
		} catch (err) {
			console.error(err);
		} finally {
			setLoading(false);
		}
	}, [currentPage, itemsPerPage, searchText]);

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

	const totalPages = Math.ceil(totalItems / itemsPerPage);

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

	function removeImageUrl(index: number) {
		setForm((prev) => ({
			...prev,
			imageUrls: prev.imageUrls.filter((_, i) => i !== index),
		}));
	}

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

	function openEdit(item: any) {
		setEditing(item);
		setForm({
			headline: item.Headline || "",
			content: item.Content || "",
			imageUrls: item.Images ? item.Images.map((img: any) => img.image) : [],
			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 {
			const submissionData = {
				...form,
				firstPara: form.headline,
				content:
					form.secondPara.length > 100
						? form.secondPara.substring(0, 100) + "..."
						: form.secondPara,
			};

			if (editing) {
				await updateNewsApi(editing.Id, submissionData);
			} else {
				await createNewsApi(submissionData);
			}
			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 flex-col md:flex-row md:justify-between md:items-center gap-4">
				<h1 className="text-3xl font-bold font-sans tracking-tight">
					News Media
				</h1>

				<div className="flex flex-wrap gap-3 items-center">
					<Input
						placeholder="Filter headline..."
						value={searchText}
						onChange={(e) => {
							setSearchText(e.target.value);
							setCurrentPage(1); // reset page
						}}
					/>

					<select
						value={itemsPerPage}
						onChange={(e) => {
							setItemsPerPage(Number(e.target.value));
							setCurrentPage(1);
						}}
						className="flex h-10 rounded-md border border-input bg-background px-3 py-2 text-sm focus:ring-2 focus:ring-primary"
					>
						<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}
						className="text-base"
					>
						<RefreshCw className="mr-2 h-5 w-5" />
						Refresh
					</Button>

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

			<Card className="shadow-sm">
				<CardHeader>
					<CardTitle className="text-xl">News Archives</CardTitle>
				</CardHeader>

				<CardContent className="p-0 sm:p-6 space-y-4">
					<div className="rounded-md border overflow-x-auto overflow-y-auto max-h-[650px] relative">
						<Table className="w-full min-w-[1000px] table-fixed border-separate border-spacing-0">
							<TableHeader className="sticky top-0 z-20 bg-background shadow-sm">
								<TableRow>
									<TableHead className="w-[80px] bg-background font-bold">
										ID
									</TableHead>
									<TableHead className="w-[100px] bg-background font-bold">
										Cover
									</TableHead>
									<TableHead className="w-[280px] bg-background font-bold">
										Headline
									</TableHead>
									<TableHead className="w-[150px] bg-background font-bold">
										Author
									</TableHead>
									<TableHead className="w-[140px] bg-background font-bold">
										Date
									</TableHead>
									<TableHead className="w-[250px] bg-background font-bold">
										Content Preview
									</TableHead>
									<TableHead className="w-[150px] bg-background font-bold text-right">
										Actions
									</TableHead>
								</TableRow>
							</TableHeader>

							<TableBody>
								{loading ? (
									<TableRow>
										<TableCell colSpan={7} className="text-center py-10">
											<Loader2 className="h-8 w-8 animate-spin mx-auto text-primary" />
										</TableCell>
									</TableRow>
								) : news.length === 0 ? (
									<TableRow>
										<TableCell
											colSpan={7}
											className="text-center text-muted-foreground py-10 text-base"
										>
											No news articles found
										</TableCell>
									</TableRow>
								) : (
									news.map((item) => (
										<TableRow key={item.Id} className="hover:bg-muted/50">
											<TableCell className="font-mono text-xs">
												{item.Id}
											</TableCell>
											<TableCell>
												{item.Images?.[0] ? (
													<img
														src={item.Images[0].image}
														className="w-10 h-10 object-cover rounded border"
														alt="cover"
													/>
												) : (
													<div className="w-10 h-10 bg-muted flex items-center justify-center rounded">
														<ImageIcon className="w-4 h-4 text-muted-foreground" />
													</div>
												)}
											</TableCell>
											<TableCell>
												<div
													className="font-semibold text-base line-clamp-2"
													title={item.Headline}
												>
													{item.Headline}
												</div>
											</TableCell>
											<TableCell className="text-sm font-medium">
												{item.Author || "-"}
											</TableCell>
											<TableCell className="text-sm">
												{item.Date
													? new Date(item.Date).toLocaleDateString()
													: "-"}
											</TableCell>
											<TableCell>
												<div className="text-sm line-clamp-2 text-muted-foreground">
													{item.Content}
												</div>
											</TableCell>
											<TableCell className="text-right">
												<div className="flex justify-end gap-2">
													<Button
														size="icon"
														variant="ghost"
														className="h-9 w-9"
														onClick={() => openView(item)}
													>
														<Eye className="h-4 w-4" />
													</Button>
													<Button
														size="icon"
														variant="ghost"
														className="h-9 w-9"
														onClick={() => openEdit(item)}
													>
														<Pencil className="h-4 w-4" />
													</Button>
													<Button
														size="icon"
														variant="ghost"
														className="h-9 w-9 text-destructive hover:bg-destructive/10"
														onClick={() => handleDelete(Number(item.Id))}
													>
														<Trash className="h-4 w-4" />
													</Button>
												</div>
											</TableCell>
										</TableRow>
									))
								)}
							</TableBody>
						</Table>
					</div>

					{!loading && totalItems > 0 && (
						<div className="flex items-center justify-between px-2 py-4 border-t">
							<div className="text-sm text-muted-foreground">
								Total <span className="font-bold">{totalItems}</span> articles
								(Page <span className="font-bold">{currentPage}</span> of{" "}
								{totalPages})
							</div>
							<div className="flex items-center gap-6">
								<div className="text-base font-semibold">
									Page {currentPage} of {totalPages}
								</div>
								<div className="flex gap-2">
									<Button
										variant="outline"
										size="icon"
										className="h-10 w-10"
										onClick={() =>
											setCurrentPage((prev) => Math.max(prev - 1, 1))
										}
										disabled={currentPage === 1}
									>
										<ChevronLeft className="h-5 w-5" />
									</Button>
									<Button
										variant="outline"
										size="icon"
										className="h-10 w-10"
										onClick={() =>
											setCurrentPage((prev) => Math.min(prev + 1, totalPages))
										}
										disabled={currentPage === totalPages || totalPages === 0}
									>
										<ChevronRight className="h-5 w-5" />
									</Button>
								</div>
							</div>
						</div>
					)}
				</CardContent>
			</Card>

			<Dialog open={openModal} onOpenChange={setOpenModal}>
				<DialogContent className="w-full !max-w-6xl max-h-[90vh] overflow-y-auto">
					<DialogHeader>
						<DialogTitle className="text-2xl font-bold">
							{editing ? "Edit News Article" : "Add New News Article"}
						</DialogTitle>
					</DialogHeader>

					<div className="grid grid-cols-1 lg:grid-cols-3 gap-8 mt-6">
						<div className="lg:col-span-2 space-y-6">
							<h3 className="font-bold text-base border-b pb-2 text-primary">
								Article Information
							</h3>
							<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
								<div className="space-y-1 col-span-2">
									<label className="text-sm font-semibold">Headline</label>
									<Input
										name="headline"
										value={form.headline}
										onChange={handleChange}
										className="text-base"
									/>
								</div>
								<div className="space-y-1">
									<label className="text-sm font-semibold">Author</label>
									<Input
										name="author"
										value={form.author}
										onChange={handleChange}
										className="text-base"
									/>
								</div>
								<div className="space-y-1">
									<label className="text-sm font-semibold">Publish Date</label>
									<Input
										type="date"
										name="date"
										value={form.date}
										onChange={handleChange}
										className="text-base"
									/>
								</div>
							</div>
							<div className="space-y-1">
								<label className="text-sm font-semibold">Story Content</label>
								<Textarea
									name="secondPara"
									value={form.secondPara}
									onChange={handleChange}
									className="min-h-[200px] text-base"
								/>
							</div>
						</div>

						{/* Image Management Sidebar */}
						<div className="space-y-6 border-l pl-6">
							<h3 className="font-bold text-base border-b pb-2 text-primary flex items-center gap-2">
								<ImageIcon className="w-4 h-4" /> Gallery Management
							</h3>

							<div className="space-y-4">
								<label className="text-sm font-semibold">Upload Images</label>
								<BytescaleUploader
									value=""
									folderPath="/news"
									onChange={(url) => {
										if (url) {
											setForm((prev) => ({
												...prev,
												imageUrls: [...prev.imageUrls, url],
											}));
										}
									}}
								/>

								<div className="grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto pr-2 mt-4">
									{form.imageUrls.map((url, index) => (
										<div
											key={index}
											className="relative group border rounded-lg overflow-hidden h-24 bg-muted"
										>
											<img
												src={url}
												alt="upload"
												className="w-full h-full object-cover"
											/>
											<button
												type="button"
												onClick={() => removeImageUrl(index)}
												className="absolute top-1 right-1 bg-destructive text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity shadow-sm"
											>
												<X className="w-3 h-3" />
											</button>
										</div>
									))}
								</div>
								{form.imageUrls.length === 0 && (
									<p className="text-xs text-muted-foreground text-center py-10 border-2 border-dashed rounded-lg">
										No images uploaded yet.
									</p>
								)}
							</div>
						</div>
					</div>

					<DialogFooter className="mt-10 pt-6 border-t">
						<Button
							variant="ghost"
							onClick={() => setOpenModal(false)}
							className="text-base"
						>
							Cancel
						</Button>
						<Button
							onClick={handleSubmit}
							className="px-10 text-base bg-primary text-white"
						>
							{editing ? "Save Changes" : "Publish Now"}
						</Button>
					</DialogFooter>
				</DialogContent>
			</Dialog>

			<Dialog open={viewOpen} onOpenChange={setViewOpen}>
				<DialogContent className="w-full !max-w-4xl max-h-[85vh] overflow-y-auto p-6">
					<DialogHeader>
						<DialogTitle className="text-2xl border-b pb-2 flex items-center gap-2">
							<Newspaper className="h-6 w-6 text-primary" /> News Preview
						</DialogTitle>
					</DialogHeader>

					{viewData && (
						<div className="space-y-6 py-4">
							<div className="space-y-2">
								<h2 className="text-2xl font-bold leading-tight">
									{viewData.Headline}
								</h2>
								<div className="flex gap-4 text-sm text-muted-foreground font-medium italic">
									<span>By: {viewData.Author || "Anonymous"}</span>
									<span>•</span>
									<span>
										{viewData.Date
											? new Date(viewData.Date).toLocaleDateString("en-IN", {
													dateStyle: "long",
												})
											: "No Date"}
									</span>
								</div>
							</div>

							<div className="grid grid-cols-3 md:grid-cols-4 gap-2">
								{viewData.Images?.map((img: any, i: number) => (
									<img
										key={i}
										src={img.image}
										className="w-full h-24 object-cover rounded-md border"
										alt="gallery"
									/>
								))}
							</div>

							<div className="space-y-5 leading-relaxed text-base">
								<div className="bg-muted/30 p-4 rounded-lg border-l-4 border-primary">
									<p className="whitespace-pre-line">{viewData.FirstPara}</p>
								</div>
								<div className="space-y-4 px-1">
									<p className="whitespace-pre-line">{viewData.SecondPara}</p>
									<hr />
									<p className="whitespace-pre-line text-muted-foreground">
										{viewData.Content}
									</p>
								</div>
							</div>
						</div>
					)}

					<DialogFooter>
						<Button
							onClick={() => setViewOpen(false)}
							className="w-full md:w-auto"
						>
							Close Preview
						</Button>
					</DialogFooter>
				</DialogContent>
			</Dialog>
		</div>
	);
}
