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

import {getAppointmentsApi, deleteAppointmentApi} from "@/api/appointment";
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 AppointmentPage() {
	const [appointments, setAppointments] = useState<any[]>([]);
	const [loading, setLoading] = useState(true);

	const [searchText, setSearchText] = useState("");
	const [filterDoctor, setFilterDoctor] = useState("");
	const [filterDepartment, setFilterDepartment] = useState("");
	const [filterDate, setFilterDate] = useState("");

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

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

	const filteredAppointments = appointments.filter((item) => {
		const matchesSearch =
			item.name?.toLowerCase().includes(searchText.toLowerCase()) ||
			item.mobileNumber?.includes(searchText) ||
			item.email?.toLowerCase().includes(searchText.toLowerCase());

		const matchesDoctor = filterDoctor
			? item.doctor?.name?.toLowerCase().includes(filterDoctor.toLowerCase())
			: true;

		const matchesDepartment = filterDepartment
			? item.department?.name
					?.toLowerCase()
					.includes(filterDepartment.toLowerCase())
			: true;

		const matchesDate = filterDate
			? new Date(item.date).toISOString().split("T")[0] === filterDate
			: true;

		return matchesSearch && matchesDoctor && matchesDepartment && matchesDate;
	});

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

	const handleExport = () => {
		const exportData = filteredAppointments.map((item) => ({
			ID: item.id,
			Name: item.name,
			Phone: item.mobileNumber,
			Email: item.email,
			Doctor: item.doctor?.name,
			Department: item.department?.name,
			Date: new Date(item.date).toLocaleDateString(),
			Message: item.message,
		}));

		exportToExcel(exportData, "appointments");
	};

	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">Appointments</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 Doctor"
						value={filterDoctor}
						onChange={(e) => setFilterDoctor(e.target.value)}
						className="w-[180px]"
					/>

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

					<Input
						type="date"
						value={filterDate}
						onChange={(e) => setFilterDate(e.target.value)}
						className="w-[180px]"
					/>

					<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>Appointment List</CardTitle>
				</CardHeader>

				<CardContent>
					<div className="overflow-x-auto">
						<Table className="min-w-[700px]">
							<TableHeader>
								<TableRow>
									<TableHead>ID</TableHead>
									<TableHead>Name</TableHead>
									<TableHead>Phone</TableHead>
									<TableHead>Email</TableHead>
									<TableHead>Doctor</TableHead>
									<TableHead>Department</TableHead>
									<TableHead>Appointment Date</TableHead>
									<TableHead>Message</TableHead>
									<TableHead>Generated on</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>
								) : filteredAppointments.length === 0 ? (
									<TableRow>
										<TableCell colSpan={9} className="text-center">
											No appointments found
										</TableCell>
									</TableRow>
								) : (
									filteredAppointments.map((item) => (
										<TableRow key={item.id}>
											<TableCell>{item.id}</TableCell>
											<TableCell>{item.name}</TableCell>
											<TableCell>{item.mobileNumber}</TableCell>
											<TableCell>{item.email}</TableCell>
											<TableCell>{item.doctor?.name}</TableCell>
											<TableCell>{item.department?.name}</TableCell>

											{/* ✅ DATE ONLY */}
											<TableCell>
												{new Date(item.date).toLocaleDateString()}
											</TableCell>

											<TableCell className="max-w-[250px] whitespace-normal">
												{item.message}
											</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>
	);
}
