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

import {
	getDepartmentsApi,
	createDepartmentApi,
	updateDepartmentApi,
	deleteDepartmentApi,
} from "@/api/department";

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

import {Input} from "@/components/ui/input";
import {Textarea} from "@/components/ui/textarea";

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

interface Department {
	departmentId: string;
	name: string;
	image?: string;
	para1: string;
	para2: string;
	para3: string;
	facilities: string;
	services: string;
}

export default function DepartmentPage() {
	const [departments, setDepartments] = useState<Department[]>([]);
	const [loading, setLoading] = useState(true);
	const [error, setError] = useState("");

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

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

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

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

	const [form, setForm] = useState<Department>({
		departmentId: "",
		name: "",
		image: "",
		para1: "",
		para2: "",
		para3: "",
		facilities: "",
		services: "",
	});

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

		try {
			const res = await getDepartmentsApi();
			setDepartments(res?.data || []);
		} catch (err) {
			if (err instanceof AxiosError) {
				setError(err.response?.data?.message || "Failed to load departments");
			} else {
				setError("Something went wrong");
			}
		} finally {
			setLoading(false);
		}
	}, []);

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

	const filteredDepartments = departments.filter(
		(dep) =>
			dep.name.toLowerCase().includes(searchText.toLowerCase()) ||
			dep.departmentId.toLowerCase().includes(searchText.toLowerCase()),
	);

	useEffect(() => {
		setCurrentPage(1);
	}, [searchText]);

	const totalPages = Math.ceil(filteredDepartments.length / itemsPerPage);
	const indexOfLastItem = currentPage * itemsPerPage;
	const indexOfFirstItem = indexOfLastItem - itemsPerPage;
	const currentItems = filteredDepartments.slice(
		indexOfFirstItem,
		indexOfLastItem,
	);

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

	function truncate(text: string, limit = 60) {
		if (!text) return "-";
		return text.length > limit ? text.substring(0, limit) + "..." : text;
	}

	function openAdd() {
		setEditing(null);
		setForm({
			departmentId: "",
			name: "",
			image: "",
			para1: "",
			para2: "",
			para3: "",
			facilities: "",
			services: "",
		});
		setOpenModal(true);
	}

	function openEdit(dep: Department) {
		setEditing(dep);
		setForm(dep);
		setOpenModal(true);
	}

	function openView(dep: Department) {
		setViewData(dep);
		setViewOpen(true);
	}

	async function handleSubmit() {
		try {
			if (editing) {
				const {departmentId, ...updateData} = form;
				await updateDepartmentApi(editing.departmentId, updateData);
			} else {
				await createDepartmentApi(form);
			}

			setOpenModal(false);
			fetchDepartments();
		} catch (error) {
			console.error(error);
		}
	}

	async function handleDelete(id: string) {
		if (!confirm("Delete this department?")) return;

		try {
			await deleteDepartmentApi(id);
			fetchDepartments();
		} 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-4">
				<h1 className="text-3xl font-bold">Departments</h1>

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

					<Button
						variant="outline"
						onClick={fetchDepartments}
						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 Department
					</Button>
				</div>
			</div>

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

			<Card>
				<CardHeader>
					<CardTitle className="text-xl">Department List</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-[900px] table-fixed border-separate border-spacing-0">
							<TableHeader className="sticky top-0 z-20 bg-background shadow-sm">
								<TableRow>
									<TableHead className="w-[100px] bg-background text-sm font-bold">
										ID
									</TableHead>
									<TableHead className="w-[200px] bg-background text-sm font-bold">
										Name
									</TableHead>
									<TableHead className="w-[250px] bg-background text-sm font-bold">
										Para 1
									</TableHead>
									<TableHead className="w-[220px] bg-background text-sm font-bold">
										Facilities
									</TableHead>
									<TableHead className="w-[220px] bg-background text-sm font-bold">
										Services
									</TableHead>
									<TableHead className="w-[140px] bg-background text-right text-sm font-bold">
										Actions
									</TableHead>
								</TableRow>
							</TableHeader>

							<TableBody>
								{loading ? (
									<TableRow>
										<TableCell colSpan={6} className="text-center py-10">
											<Loader2 className="h-8 w-8 animate-spin mx-auto" />
										</TableCell>
									</TableRow>
								) : currentItems.length === 0 ? (
									<TableRow>
										<TableCell
											colSpan={6}
											className="text-center text-muted-foreground py-10 text-base"
										>
											No departments found
										</TableCell>
									</TableRow>
								) : (
									currentItems.map((dep) => (
										<TableRow
											key={dep.departmentId}
											className="hover:bg-muted/50"
										>
											<TableCell className="font-mono text-xs">
												{dep.departmentId}
											</TableCell>

											<TableCell>
												<div
													className="font-semibold text-base truncate"
													title={dep.name}
												>
													{dep.name}
												</div>
											</TableCell>

											<TableCell>
												<div className="text-sm break-words whitespace-normal">
													{truncate(dep.para1)}
												</div>
											</TableCell>

											<TableCell>
												<div className="text-sm break-words whitespace-normal">
													{truncate(dep.facilities)}
												</div>
											</TableCell>

											<TableCell>
												<div className="text-sm break-words whitespace-normal">
													{truncate(dep.services)}
												</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(dep)}
													>
														<Eye className="h-4 w-4" />
													</Button>

													<Button
														size="icon"
														variant="ghost"
														className="h-9 w-9"
														onClick={() => openEdit(dep)}
													>
														<Pencil className="h-4 w-4" />
													</Button>

													<Button
														size="icon"
														variant="ghost"
														className="h-9 w-9 text-destructive hover:text-destructive hover:bg-destructive/10"
														onClick={() => handleDelete(dep.departmentId)}
													>
														<Trash className="h-4 w-4" />
													</Button>
												</div>
											</TableCell>
										</TableRow>
									))
								)}
							</TableBody>
						</Table>
					</div>

					{!loading && filteredDepartments.length > 0 && (
						<div className="flex items-center justify-between px-2 py-6 border-t">
							<div className="text-base text-muted-foreground">
								Showing{" "}
								<span className="font-semibold">{indexOfFirstItem + 1}</span> to{" "}
								<span className="font-semibold">
									{Math.min(indexOfLastItem, filteredDepartments.length)}
								</span>{" "}
								of{" "}
								<span className="font-semibold">
									{filteredDepartments.length}
								</span>{" "}
								departments
							</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-5xl max-h-[90vh] overflow-y-auto">
					<DialogHeader>
						<DialogTitle>
							{editing ? "Edit Department" : "Add Department"}
						</DialogTitle>
					</DialogHeader>

					<div className="space-y-4">
						<div className="space-y-2">
							<label className="text-sm font-semibold">Department Image</label>
							<BytescaleUploader
								value={form.image}
								folderPath="/departments"
								onChange={(url) => setForm({...form, image: url})}
							/>
						</div>
						<Input
							name="departmentId"
							value={form.departmentId}
							onChange={handleChange}
							disabled={!!editing}
							placeholder="Department ID"
						/>

						<Input
							name="name"
							value={form.name}
							onChange={handleChange}
							placeholder="Department Name"
						/>

						<Textarea
							name="para1"
							value={form.para1}
							onChange={handleChange}
							placeholder="Para1"
						/>
						<Textarea
							name="para2"
							value={form.para2}
							onChange={handleChange}
							placeholder="Para2"
						/>
						<Textarea
							name="para3"
							value={form.para3}
							onChange={handleChange}
							placeholder="Para3"
						/>
						<Textarea
							name="facilities"
							value={form.facilities}
							onChange={handleChange}
							placeholder="Facilities"
						/>
						<Textarea
							name="services"
							value={form.services}
							onChange={handleChange}
							placeholder="Services"
						/>
					</div>

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

			<Dialog open={viewOpen} onOpenChange={setViewOpen}>
				<DialogContent className="w-full !max-w-5xl max-h-[90vh] overflow-y-auto">
					<DialogHeader>
						<DialogTitle>Department Details</DialogTitle>
					</DialogHeader>
					{viewData && (
						<div className="space-y-4 text-sm">
							<p>
								<b>ID:</b> {viewData.departmentId}
							</p>
							<p>
								<b>Name:</b> {viewData.name}
							</p>
							<p>
								<b>Para1:</b>
								<br />
								{viewData.para1}
							</p>
							<p>
								<b>Para2:</b>
								<br />
								{viewData.para2}
							</p>
							<p>
								<b>Para3:</b>
								<br />
								{viewData.para3}
							</p>
							<p>
								<b>Facilities:</b>
								<br />
								{viewData.facilities}
							</p>
							<p>
								<b>Services:</b>
								<br />
								{viewData.services}
							</p>
						</div>
					)}
					<DialogFooter>
						<Button onClick={() => setViewOpen(false)}>Close</Button>
					</DialogFooter>
				</DialogContent>
			</Dialog>
		</div>
	);
}
