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 { Loader2, Plus, Pencil, Trash, RefreshCw } 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 [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()),
	);

	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 justify-between items-center gap-3 flex-wrap">
				<h1 className="text-2xl font-bold">Careers</h1>

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

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

			<Card>
				<CardHeader>
					<CardTitle>Career List</CardTitle>
				</CardHeader>

				<CardContent>
					<div className="overflow-x-auto">
						<Table className="min-w-[900px]">
							<TableHeader>
								<TableRow>
									<TableHead>ID</TableHead>
									<TableHead>Post</TableHead>
									<TableHead>Designation</TableHead>
									<TableHead>Qualification</TableHead>
									<TableHead>Experience</TableHead>
									<TableHead>Email</TableHead>
									<TableHead>Phone</TableHead>
									<TableHead>Status</TableHead>
									<TableHead>Actions</TableHead>
								</TableRow>
							</TableHeader>

							<TableBody>
								{loading ? (
									<TableRow>
										<TableCell colSpan={9} className="text-center">
											<Loader2 className="h-6 w-6 animate-spin mx-auto" />
										</TableCell>
									</TableRow>
								) : filteredCareers.length === 0 ? (
									<TableRow>
										<TableCell colSpan={9} className="text-center">
											No careers found
										</TableCell>
									</TableRow>
								) : (
									filteredCareers.map((item) => (
										<TableRow key={item.id}>
											<TableCell>{item.id}</TableCell>
											<TableCell>{item.post}</TableCell>
											<TableCell>{item.designation}</TableCell>
											<TableCell>{item.qualification}</TableCell>
											<TableCell>{item.experienceNeed}</TableCell>
											<TableCell>{item.email}</TableCell>
											<TableCell>{item.number}</TableCell>
											<TableCell>{item.status}</TableCell>

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

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

			{/* MODAL */}
			<Dialog open={openModal} onOpenChange={setOpenModal}>
				<DialogContent>
					<DialogHeader>
						<DialogTitle>{editing ? "Edit Career" : "Add Career"}</DialogTitle>
					</DialogHeader>

					<div className="space-y-3">
						<Input
							name="post"
							placeholder="Post"
							value={form.post}
							onChange={handleChange}
						/>
						<Input
							name="designation"
							placeholder="Designation"
							value={form.designation}
							onChange={handleChange}
						/>
						<Input
							name="qualification"
							placeholder="Qualification"
							value={form.qualification}
							onChange={handleChange}
						/>
						<Input
							name="experienceNeed"
							placeholder="Experience Needed"
							value={form.experienceNeed}
							onChange={handleChange}
						/>
						<Input
							name="email"
							placeholder="Email"
							value={form.email}
							onChange={handleChange}
						/>
						<Input
							name="number"
							placeholder="Phone Number"
							value={form.number}
							onChange={handleChange}
						/>
						<Input
							name="status"
							placeholder="Status"
							value={form.status}
							onChange={handleChange}
						/>
					</div>

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