import { useState, useEffect, useCallback } from "react";
import { getAllInquiriesApi, HealthInquiry } from "@/api/healthCheck";

import {
	Table,
	TableBody,
	TableCell,
	TableHead,
	TableHeader,
	TableRow,
} from "@/components/ui/table";
import {
	Tooltip,
	TooltipContent,
	TooltipProvider,
	TooltipTrigger,
} from "@/components/ui/tooltip";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Loader2, RefreshCw, ChevronLeft, ChevronRight } from "lucide-react";

export default function PackageInquiriesTab() {
	const [inquiries, setInquiries] = useState<HealthInquiry[]>([]);
	const [loading, setLoading] = useState(true);

	const [filterDate, setFilterDate] = useState("");
	const [startDate, setStartDate] = useState("");
	const [endDate, setEndDate] = useState("");

	const [currentPage, setCurrentPage] = useState(1);
	const [itemsPerPage, setItemsPerPage] = useState(10);
	const [totalItems, setTotalItems] = useState(0);
	const [totalPages, setTotalPages] = useState(1);

	const fetchInquiries = useCallback(async () => {
		setLoading(true);
		try {
			const res = await getAllInquiriesApi(
				currentPage,
				itemsPerPage,
				filterDate,
				startDate,
				endDate,
			);
			setInquiries(res.data || []);
			setTotalItems(res.pagination?.total || 0);
			setTotalPages(res.pagination?.totalPages || 1);
		} catch (err) {
			console.error("Failed to fetch inquiries", err);
		} finally {
			setLoading(false);
		}
	}, [currentPage, itemsPerPage, filterDate, startDate, endDate]);

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

	const handleFilterChange = (
		setter: React.Dispatch<React.SetStateAction<string>>,
		value: string,
	) => {
		setter(value);
		setCurrentPage(1);
	};

	const indexOfFirstItem = (currentPage - 1) * itemsPerPage;
	const indexOfLastItem = Math.min(currentPage * itemsPerPage, totalItems);

	return (
		<Card>
			<CardHeader className="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
				<CardTitle className="text-xl">Package Inquiries</CardTitle>

				<div className="flex flex-wrap items-end gap-3">
					<div className="flex flex-col gap-1">
						<label className="text-xs font-medium text-muted-foreground">
							Specific Date
						</label>
						<Input
							type="date"
							value={filterDate}
							onChange={(e) =>
								handleFilterChange(setFilterDate, e.target.value)
							}
							className="w-[140px] text-sm"
							disabled={!!startDate || !!endDate}
						/>
					</div>

					<div className="flex flex-col gap-1">
						<label className="text-xs font-medium text-muted-foreground">
							From
						</label>
						<Input
							type="date"
							value={startDate}
							onChange={(e) => handleFilterChange(setStartDate, e.target.value)}
							className="w-[140px] text-sm"
							disabled={!!filterDate}
						/>
					</div>

					<div className="flex flex-col gap-1">
						<label className="text-xs font-medium text-muted-foreground">
							To
						</label>
						<Input
							type="date"
							value={endDate}
							onChange={(e) => handleFilterChange(setEndDate, e.target.value)}
							className="w-[140px] text-sm"
							disabled={!!filterDate}
						/>
					</div>

					<div className="flex flex-col gap-1">
						<label className="text-xs font-medium text-muted-foreground">
							Rows
						</label>
						<select
							value={itemsPerPage}
							onChange={(e) => {
								setItemsPerPage(Number(e.target.value));
								setCurrentPage(1);
							}}
							className="flex h-10 rounded-md border border-input bg-background px-3 py-2 text-sm focus:ring-2 focus:ring-primary">
							<option value={5}>5 / page</option>
							<option value={10}>10 / page</option>
							<option value={20}>20 / page</option>
							<option value={50}>50 / page</option>
						</select>
					</div>

					<Button variant="outline" onClick={fetchInquiries} disabled={loading}>
						<RefreshCw
							className={`mr-2 h-4 w-4 ${loading ? "animate-spin" : ""}`}
						/>
						Refresh
					</Button>
				</div>
			</CardHeader>
			<CardContent className="p-0 sm:p-6 sm:pt-0">
				<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-[150px] font-bold bg-background">
									Requested Date
								</TableHead>
								<TableHead className="w-[220px] font-bold bg-background">
									Patient Details
								</TableHead>
								<TableHead className="w-[250px] font-bold bg-background">
									Requested Package
								</TableHead>
								<TableHead className="w-[120px] font-bold bg-background">
									Age/Gender
								</TableHead>
								<TableHead className="w-[250px] font-bold bg-background">
									Message
								</TableHead>
							</TableRow>
						</TableHeader>
						<TableBody>
							{loading ? (
								<TableRow>
									<TableCell colSpan={5} className="text-center py-10">
										<Loader2 className="h-8 w-8 animate-spin mx-auto" />
									</TableCell>
								</TableRow>
							) : inquiries.length === 0 ? (
								<TableRow>
									<TableCell
										colSpan={5}
										className="text-center text-muted-foreground py-10">
										No inquiries found for the selected criteria
									</TableCell>
								</TableRow>
							) : (
								inquiries.map((inq) => (
									<TableRow key={inq.id} className="hover:bg-muted/50">
										<TableCell>
											<div className="font-semibold text-primary">
												{new Date(inq.preferredDate).toLocaleDateString()}
											</div>
											<div className="text-[11px] text-muted-foreground mt-1">
												Submitted:{" "}
												{new Date(inq.createdAt).toLocaleDateString()}
											</div>
										</TableCell>
										<TableCell>
											<div className="font-semibold text-base">
												{inq.fullName}
											</div>
											<div className="text-sm">{inq.mobileNumber}</div>
											<div className="text-xs text-muted-foreground">
												{inq.email || "-"}
											</div>
										</TableCell>
										<TableCell>
											<div className="font-semibold text-sm truncate">
												{inq.healthPackage?.name || "N/A"}
											</div>
										</TableCell>
										<TableCell>
											<div className="font-medium">
												{inq.age} yrs / {inq.gender}
											</div>
										</TableCell>
										<TooltipProvider>
											<Tooltip>
												<TooltipTrigger asChild>
													<div className="text-sm italic line-clamp-3 text-muted-foreground whitespace-pre-wrap cursor-pointer">
														{inq.message || "No message provided."}
													</div>
												</TooltipTrigger>

												<TooltipContent className="max-w-md whitespace-pre-wrap">
													{inq.message || "No message provided."}
												</TooltipContent>
											</Tooltip>
										</TooltipProvider>
									</TableRow>
								))
							)}
						</TableBody>
					</Table>
				</div>

				{!loading && totalItems > 0 && (
					<div className="flex flex-col sm:flex-row items-center justify-between px-2 py-4 border-t gap-4 mt-2">
						<div className="text-sm text-muted-foreground">
							Showing{" "}
							<span className="font-semibold">{indexOfFirstItem + 1}</span> to{" "}
							<span className="font-semibold">{indexOfLastItem}</span> of{" "}
							<span className="font-semibold">{totalItems}</span> inquiries
						</div>
						<div className="flex items-center gap-6">
							<div className="text-sm font-semibold">
								Page {currentPage} of {totalPages || 1}
							</div>
							<div className="flex gap-2">
								<Button
									variant="outline"
									size="icon"
									className="h-9 w-9"
									onClick={() =>
										setCurrentPage((prev) => Math.max(prev - 1, 1))
									}
									disabled={currentPage === 1}>
									<ChevronLeft className="h-4 w-4" />
								</Button>
								<Button
									variant="outline"
									size="icon"
									className="h-9 w-9"
									onClick={() =>
										setCurrentPage((prev) => Math.min(prev + 1, totalPages))
									}
									disabled={currentPage === totalPages || totalPages === 0}>
									<ChevronRight className="h-4 w-4" />
								</Button>
							</div>
						</div>
					</div>
				)}
			</CardContent>
		</Card>
	);
}
