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

import { getCareersApi, deleteCareerApi } from "@/api/career";
import apiClient from "@/api/client";

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

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

export default function CareerPage() {
	const [careers, setCareers] = useState<any[]>([]);
	const [loading, setLoading] = useState(true);

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

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

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

	const [form, setForm] = useState({
		post: "",
		designation: "",
		qualification: "",
		experienceNeed: "",
		email: "",
		number: "",
		status: "new",
	});

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

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

	const filteredCareers = careers.filter(
		(item) =>
			item.post?.toLowerCase().includes(searchText.toLowerCase()) ||
			item.designation?.toLowerCase().includes(searchText.toLowerCase()),
	);

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

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

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

	function openAdd() {
		setEditing(null);
		setForm({
			post: "",
			designation: "",
			qualification: "",
			experienceNeed: "",
			email: "",
			number: "",
			status: "new",
		});
		setOpenModal(true);
	}

	function openEdit(item: any) {
		setEditing(item);
		setForm({
			post: item.post || "",
			designation: item.designation || "",
			qualification: item.qualification || "",
			experienceNeed: item.experienceNeed || "",
			email: item.email || "",
			number: item.number || "",
			status: item.status || "new",
		});
		setOpenModal(true);
	}

	async function handleSubmit() {
		try {
			if (editing) {
				await apiClient.patch(`/careers/${editing.id}`, form);
			} else {
				await apiClient.post("/careers", form);
			}
			setOpenModal(false);
			fetchAll();
		} catch (err) {
			console.error(err);
		}
	}

	async function handleDelete(id: number) {
		if (!confirm("Delete career?")) return;
		await deleteCareerApi(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">Careers</h1>

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

					<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 Career
					</Button>
				</div>
			</div>

			<Card>
				<CardHeader>
					<CardTitle className="text-xl">Career Opportunities</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-[60px] bg-background font-bold text-sm">
										ID
									</TableHead>
									<TableHead className="w-[200px] bg-background font-bold text-sm">
										Post & Designation
									</TableHead>
									<TableHead className="w-[200px] bg-background font-bold text-sm">
										Qualification
									</TableHead>
									<TableHead className="w-[120px] bg-background font-bold text-sm">
										Experience
									</TableHead>
									<TableHead className="w-[200px] bg-background font-bold text-sm">
										Contact Info
									</TableHead>
									<TableHead className="w-[100px] bg-background font-bold text-sm">
										Status
									</TableHead>
									<TableHead className="w-[120px] bg-background font-bold text-right text-sm">
										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" />
										</TableCell>
									</TableRow>
								) : currentItems.length === 0 ? (
									<TableRow>
										<TableCell
											colSpan={7}
											className="text-center text-muted-foreground py-10 text-base"
										>
											No careers found
										</TableCell>
									</TableRow>
								) : (
									currentItems.map((item) => (
										<TableRow key={item.id} className="hover:bg-muted/50">
											<TableCell className="font-mono text-xs">
												{item.id}
											</TableCell>
											<TableCell>
												<div className="font-semibold text-base truncate">
													{item.post}
												</div>
												<div className="text-xs text-muted-foreground truncate">
													{item.designation}
												</div>
											</TableCell>
											<TableCell>
												<div className="text-sm line-clamp-2">
													{item.qualification}
												</div>
											</TableCell>
											<TableCell className="text-sm">
												{item.experienceNeed}
											</TableCell>
											<TableCell>
												<div className="text-sm font-medium">{item.email}</div>
												<div className="text-xs text-muted-foreground">
													{item.number}
												</div>
											</TableCell>
											<TableCell>
												<Badge
													variant={
														item.status === "active" ? "default" : "secondary"
													}
													className="capitalize"
												>
													{item.status}
												</Badge>
											</TableCell>

											<TableCell className="text-right">
												<div className="flex justify-end gap-2">
													<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:text-destructive hover:bg-destructive/10"
														onClick={() => handleDelete(item.id)}
													>
														<Trash className="h-4 w-4" />
													</Button>
												</div>
											</TableCell>
										</TableRow>
									))
								)}
							</TableBody>
						</Table>
					</div>

					{!loading && filteredCareers.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, filteredCareers.length)}
								</span>{" "}
								of{" "}
								<span className="font-semibold">{filteredCareers.length}</span>{" "}
								careers
							</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-lg">
					<DialogHeader>
						<DialogTitle className="text-2xl">
							{editing ? "Edit Career" : "Add New Career"}
						</DialogTitle>
					</DialogHeader>

					<div className="space-y-4 py-4">
						<div className="grid grid-cols-1 gap-4">
							<Input
								name="post"
								placeholder="Post (e.g. Staff Nurse)"
								value={form.post}
								onChange={handleChange}
								className="text-base"
							/>
							<Input
								name="designation"
								placeholder="Designation"
								value={form.designation}
								onChange={handleChange}
								className="text-base"
							/>
							<Input
								name="qualification"
								placeholder="Qualification"
								value={form.qualification}
								onChange={handleChange}
								className="text-base"
							/>
							<Input
								name="experienceNeed"
								placeholder="Experience Needed"
								value={form.experienceNeed}
								onChange={handleChange}
								className="text-base"
							/>
							<Input
								name="email"
								type="email"
								placeholder="HR Email Address"
								value={form.email}
								onChange={handleChange}
								className="text-base"
							/>
							<Input
								name="number"
								placeholder="Contact Number"
								value={form.number}
								onChange={handleChange}
								className="text-base"
							/>
							<Input
								name="status"
								placeholder="Status (e.g. active / closed)"
								value={form.status}
								onChange={handleChange}
								className="text-base"
							/>
						</div>
					</div>

					<DialogFooter className="pt-4 border-t">
						<Button
							variant="ghost"
							onClick={() => setOpenModal(false)}
							className="text-base"
						>
							Cancel
						</Button>
						<Button onClick={handleSubmit} className="px-8 text-base">
							{editing ? "Save Changes" : "Create Career"}
						</Button>
					</DialogFooter>
				</DialogContent>
			</Dialog>
		</div>
	);
}
