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

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} from "lucide-react";

interface Department {
	departmentId: string;
	name: 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 [searchText, setSearchText] = useState("");

	const [form, setForm] = useState<Department>({
		departmentId: "",
		name: "",
		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) => {
		const text = searchText.toLowerCase();

		return (
			dep.name.toLowerCase().includes(text) ||
			dep.departmentId.toLowerCase().includes(text) ||
			dep.para1.toLowerCase().includes(text) ||
			dep.para2.toLowerCase().includes(text) ||
			dep.para3.toLowerCase().includes(text) ||
			dep.facilities.toLowerCase().includes(text) ||
			dep.services.toLowerCase().includes(text)
		);
	});

	function handleChange(
		e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
	) {
		setForm({
			...form,
			[e.target.name]: e.target.value,
		});
	}

	function openAdd() {
		setEditing(null);

		setForm({
			departmentId: "",
			name: "",
			para1: "",
			para2: "",
			para3: "",
			facilities: "",
			services: "",
		});

		setOpenModal(true);
	}

	function openEdit(dep: Department) {
		setEditing(dep);
		setForm(dep);
		setOpenModal(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(departmentId: string) {
		const confirmDelete = confirm("Delete this department?");
		if (!confirmDelete) return;

		try {
			await deleteDepartmentApi(departmentId);
			fetchDepartments();
		} catch (error) {
			console.error(error);
		}
	}

	return (
		<div className="p-6 space-y-6">
			{/* HEADER */}
			<div className="flex flex-col md:flex-row md:justify-between md:items-center gap-3">
				<h1 className="text-2xl 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-[220px]"
					/>

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

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

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

			<Card>
				<CardHeader>
					<CardTitle>Department List</CardTitle>
				</CardHeader>

				<CardContent>
					<div className="border rounded-md overflow-x-auto max-w-full">
						<Table>
							<TableHeader>
								<TableRow>
									<TableHead>ID</TableHead>
									<TableHead>Name</TableHead>
									<TableHead>Para1</TableHead>
									<TableHead>Para2</TableHead>
									<TableHead>Para3</TableHead>
									<TableHead>Facilities</TableHead>
									<TableHead>Services</TableHead>
									<TableHead>Actions</TableHead>
								</TableRow>
							</TableHeader>

							<TableBody>
								{loading ? (
									<TableRow>
										<TableCell colSpan={8} className="text-center">
											<Loader2 className="h-6 w-6 animate-spin mx-auto" />
										</TableCell>
									</TableRow>
								) : filteredDepartments.length === 0 ? (
									<TableRow>
										<TableCell colSpan={8} className="text-center">
											No departments found
										</TableCell>
									</TableRow>
								) : (
									filteredDepartments.map((dep) => (
										<TableRow key={dep.departmentId}>
											<TableCell>{dep.departmentId}</TableCell>

											<TableCell>{dep.name}</TableCell>

											<TableCell className="max-w-[300px] whitespace-normal break-words">
												{dep.para1}
											</TableCell>

											<TableCell className="max-w-[300px] whitespace-normal break-words">
												{dep.para2}
											</TableCell>

											<TableCell className="max-w-[300px] whitespace-normal break-words">
												{dep.para3}
											</TableCell>

											<TableCell className="max-w-[300px] whitespace-normal break-words">
												{dep.facilities}
											</TableCell>

											<TableCell className="max-w-[300px] whitespace-normal break-words">
												{dep.services}
											</TableCell>

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

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

			{/* MODAL */}
			<Dialog open={openModal} onOpenChange={setOpenModal}>
				<DialogContent className="max-w-4xl">
					<DialogHeader>
						<DialogTitle>
							{editing ? "Edit Department" : "Add Department"}
						</DialogTitle>
					</DialogHeader>

					<div className="space-y-4 max-h-[70vh] overflow-y-auto pr-2">
						<Input
							name="departmentId"
							placeholder="Department ID"
							value={form.departmentId}
							onChange={handleChange}
							disabled={!!editing}
						/>

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

						<Textarea
							name="para1"
							placeholder="Paragraph 1"
							value={form.para1}
							onChange={handleChange}
						/>

						<Textarea
							name="para2"
							placeholder="Paragraph 2"
							value={form.para2}
							onChange={handleChange}
						/>

						<Textarea
							name="para3"
							placeholder="Paragraph 3"
							value={form.para3}
							onChange={handleChange}
						/>

						<Textarea
							name="facilities"
							placeholder="Facilities"
							value={form.facilities}
							onChange={handleChange}
						/>

						<Textarea
							name="services"
							placeholder="Services"
							value={form.services}
							onChange={handleChange}
						/>
					</div>

					<DialogFooter>
						<Button variant="outline" onClick={() => setOpenModal(false)}>
							Cancel
						</Button>

						<Button onClick={handleSubmit}>
							{editing ? "Update" : "Create"}
						</Button>
					</DialogFooter>
				</DialogContent>
			</Dialog>
		</div>
	);
}
