import React from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { TooltipProvider, Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
import { Info, Clipboard, ChartPie, Pencil, Trash2, ArrowUpDown, ArrowUp, ArrowDown } from "lucide-react";
import { toast } from "sonner";
import StatusBadge from "../common/StatusBadge";
import PollTableSkeleton from "./PollTableSkeleton";
import { __, _x } from "@wordpress/i18n";

/**
 * PollTable - Displays a table of polls with actions
 */
export const PollTable = ({ polls, isLoading = false, onDelete, filters, onSort }) => {
	const navigate = useNavigate();
	const [searchParams] = useSearchParams();

	// Handle column sorting
	const handleSort = (column) => {
		if (!onSort) return;

		const isCurrentSort = filters?.sort_by === column;
		const newOrder = isCurrentSort && filters?.sort_order === "asc" ? "desc" : "asc";
		onSort(column, newOrder);
	};

	// Get sort icon for column
	const getSortIcon = (column) => {
		if (filters?.sort_by !== column) {
			return <ArrowUpDown size={14} className="opacity-50" />;
		}
		return filters?.sort_order === "asc" ? <ArrowUp size={14} /> : <ArrowDown size={14} />;
	};

	// Sortable header component
	const SortableHeader = ({ column, children, className = "" }) => {
		if (!onSort) {
			return <TableHead className={className}>{children}</TableHead>;
		}

		return (
			<TableHead className={className}>
				<Button
					variant="ghost"
					size="sm"
					onClick={() => handleSort(column)}
					className="h-auto !p-0 hover:bg-transparent font-medium flex items-center gap-1">
					{children}
					{getSortIcon(column)}
				</Button>
			</TableHead>
		);
	};

	// Handle shortcode copy to clipboard
	const handleCopyShortcode = (id) => {
		const shortcode = `[socialpoll id=${id}]`;
		navigator.clipboard.writeText(shortcode);
		toast.success(__("Shortcode copied to clipboard", "socialpoll"));
	};

	// Handle navigation to poll detail page
	const handleViewStats = (poll) => {
		const params = searchParams.toString();
		navigate(`/poll/${poll.id}${params ? `?${params}` : ''}`);
	};

	// Handle navigation to edit poll page
	const handleEditPoll = (poll) => {
		const params = searchParams.toString();
		navigate(`/edit/${poll.id}${params ? `?${params}` : ''}`);
	};

	if (isLoading) {
		return <PollTableSkeleton rows={5} />;
	}

	return (
		<Table>
			<TableHeader>
				<TableRow>
					<SortableHeader column="id" className="w-[60px]">
						# {_x("ID", "table header", "socialpoll")}
					</SortableHeader>
					<SortableHeader column="name" className="w-[400px]">
						{_x("Poll", "table header", "socialpoll")}
					</SortableHeader>
					<SortableHeader column="visibility_status">{_x("Visibility", "table header", "socialpoll")}</SortableHeader>
					<TableHead>{_x("Publish Status", "table header", "socialpoll")}</TableHead>
					<TableHead>{_x("Participation", "table header", "socialpoll")}</TableHead>
					<TableHead>{_x("Most voted option", "table header", "socialpoll")}</TableHead>
					<TableHead className="text-right">{_x("Shortcode", "table header", "socialpoll")}</TableHead>
					<TableHead className="text-right">{_x("Actions", "table header", "socialpoll")}</TableHead>
				</TableRow>
			</TableHeader>
			<TableBody>
				{polls.length === 0 ? (
					<TableRow>
						<TableCell colSpan={7} className="h-24 text-center">
							{__("No polls found.", "socialpoll")}
						</TableCell>
					</TableRow>
				) : (
					polls.map((poll) => (
						<TableRow key={poll.id}>
							<TableCell className="font-medium">{poll.id}</TableCell>
							<TableCell>
								<Button variant="link" onClick={() => handleViewStats(poll)} className="!p-0">
									{poll.name}
								</Button>
							</TableCell>
							<TableCell>
								<StatusBadge status={poll.visibility_status || poll.status} />
							</TableCell>
							<TableCell>
								<StatusBadge type="publish" isPublished={poll.is_published} />
							</TableCell>
							<TableCell>
								<div
									className="flex flex-row items-center gap-2 cursor-pointer max-w-fit"
									onClick={() => handleViewStats(poll)}>
									{poll.participationRate} %
									<TooltipProvider>
										<Tooltip>
											<TooltipTrigger>
												<Info size={20} />
											</TooltipTrigger>
											<TooltipContent side="right">
												<span>
													<strong>{poll.totalVotes}</strong> {__("votes out of", "socialpoll")}{" "}
													<strong>{poll.totalVisits}</strong> {__("visits", "socialpoll")}
												</span>
											</TooltipContent>
										</Tooltip>
									</TooltipProvider>
								</div>
							</TableCell>
							<TableCell className="text-left">
								<div
									className="flex flex-row items-center gap-2 cursor-pointer max-w-fit"
									onClick={() => handleViewStats(poll)}>
									{poll.mostVotedOption}
								</div>
							</TableCell>
							<TableCell>
								<div className="flex flex-row items-center gap-2 justify-end">
									<Button variant="outline" size="sm" className="w-auto" onClick={() => handleCopyShortcode(poll.id)}>
										<span className="text-gray-500">[socialpoll id={poll.id}]</span>
										<Clipboard size={16} className="text-gray-500 ml-2" />
									</Button>
								</div>
							</TableCell>
							<TableCell className="text-right flex flex-row justify-end gap-2">
								<Button variant="outline" size="icon" onClick={() => handleViewStats(poll)}>
									<ChartPie />
								</Button>
								<Button
									variant="outline"
									size="icon"
									onClick={() => handleEditPoll(poll)}
									/* disabled={poll.is_published}
									className={poll.is_published ? "opacity-50 cursor-not-allowed" : ""} */
								>
									<Pencil />
								</Button>
								<Button variant="outline" size="icon" onClick={() => onDelete(poll)}>
									<Trash2 className="text-red-500" />
								</Button>
							</TableCell>
						</TableRow>
					))
				)}
			</TableBody>
		</Table>
	);
};

export default PollTable;
