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

import { getCandidatesApi, deleteCandidateApi } from "@/api/candidates";
import { exportToExcel } from "@/utils/exportToExcel";

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 { Loader2, Trash, RefreshCw, Download } from "lucide-react";

export default function CandidatePage() {
	const [candidates, setCandidates] = useState<any[]>([]);
	const [loading, setLoading] = useState(true);

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

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

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

	const filteredCandidates = candidates.filter((item) => {
		const matchesSearch =
			item.fullName?.toLowerCase().includes(searchText.toLowerCase()) ||
			item.mobile?.includes(searchText) ||
			item.email?.toLowerCase().includes(searchText.toLowerCase());

		const matchesCareer = filterCareer
			? item.career?.post?.toLowerCase().includes(filterCareer.toLowerCase())
			: true;

		return matchesSearch && matchesCareer;
	});

	async function handleDelete(id: number) {
		if (!confirm("Delete candidate?")) return;
		await deleteCandidateApi(id);
		fetchAll();
	}

	const handleExport = () => {
		const exportData = filteredCandidates.map((item) => ({
			ID: item.id,
			Name: item.fullName,
			Phone: item.mobile,
			Email: item.email,
			Career: item.career?.post,
			Designation: item.career?.designation,
			Subject: item.subject,
			CoverLetter: item.coverLetter,
			Date: new Date(item.createdAt).toLocaleDateString(),
		}));

		exportToExcel(exportData, "candidates");
	};

	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">Candidates</h1>

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

					<Input
						placeholder="Filter Career"
						value={filterCareer}
						onChange={(e) => setFilterCareer(e.target.value)}
						className="w-[200px]"
					/>

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

					<Button variant="outline" onClick={handleExport}>
						<Download className="mr-2 h-4 w-4" />
						Export
					</Button>
				</div>
			</div>

			<Card>
				<CardHeader>
					<CardTitle>Candidate List</CardTitle>
				</CardHeader>

				<CardContent>
					<div className="overflow-x-auto">
						<Table className="min-w-[900px]">
							<TableHeader>
								<TableRow>
									<TableHead>ID</TableHead>
									<TableHead>Name</TableHead>
									<TableHead>Phone</TableHead>
									<TableHead>Email</TableHead>
									<TableHead>Career</TableHead>
									<TableHead>Designation</TableHead>
									<TableHead>Subject</TableHead>
									<TableHead>Cover Letter</TableHead>
									<TableHead>Applied On</TableHead>
									<TableHead>Actions</TableHead>
								</TableRow>
							</TableHeader>

							<TableBody>
								{loading ? (
									<TableRow>
										<TableCell colSpan={10} className="text-center">
											<Loader2 className="h-6 w-6 animate-spin mx-auto" />
										</TableCell>
									</TableRow>
								) : filteredCandidates.length === 0 ? (
									<TableRow>
										<TableCell colSpan={10} className="text-center">
											No candidates found
										</TableCell>
									</TableRow>
								) : (
									filteredCandidates.map((item) => (
										<TableRow key={item.id}>
											<TableCell>{item.id}</TableCell>
											<TableCell>{item.fullName}</TableCell>
											<TableCell>{item.mobile}</TableCell>
											<TableCell>{item.email}</TableCell>

											<TableCell>{item.career?.post}</TableCell>
											<TableCell>{item.career?.designation}</TableCell>

											<TableCell>{item.subject}</TableCell>

											<TableCell className="max-w-[250px] whitespace-normal">
												{item.coverLetter}
											</TableCell>

											<TableCell>
												{new Date(item.createdAt).toLocaleDateString()}
											</TableCell>

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