import type { ColumnDef } from "@tanstack/react-table";
import {
	Crown,
	Mail,
	MessagesSquare,
	MoreHorizontal,
	Paperclip,
	Search,
	ShoppingBag,
	User,
	UserCog,
} from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/router";
import toast from "react-hot-toast";
import { DataTable } from "~/components/custom_ui/data-table";
import { DataTableColumnHeader } from "~/components/custom_ui/dataTable-header";
import type {
	PinnedFiltro,
	SearchFiltro,
} from "~/components/custom_ui/dataTable-toolbar";
import { Button } from "~/components/ui/button";
import {
	DropdownMenu,
	DropdownMenuContent,
	DropdownMenuItem,
	DropdownMenuLabel,
	DropdownMenuSeparator,
	DropdownMenuTrigger,
} from "~/components/ui/dropdown-menu";
import { UserAvatar } from "~/components/user_avatar";
import { cn } from "~/lib/utils";
import type { Users } from "~/schemas/public/Users";
import { api } from "~/utils/api";

type UserWChatInfo = Pick<
	Users,
	"id" | "username" | "email" | "isAdmin" | "isBlocked" | "created_at"
> & { chatid: string | null };

export const UsersTable = (props: { data: UserWChatInfo[] }) => {
	const router = useRouter();
	const { mutateAsync: swap } = api.auth.swapUser.useMutation({
		onSuccess: async () => {
			toast.success("Utente cambiato con successo");
			await router.push("/area-riservata/load-page");
		},
	});

	const { data } = props;

	const tabledata = data.map((user) => {
		return {
			actions: "Azioni",
			chatid: user.chatid,
			created_at: user.created_at,
			email: user.email,
			id: user.id,
			isAdmin: user.isAdmin ? "Admin" : "Utente",
			isBanned: user.isBlocked ? "Bloccato" : "Attivo",
			username: user.username,
		};
	});

	const admin_options = [
		{ label: "Admin", value: "Admin" },
		{ label: "Utente", value: "Utente" },
	];

	const columns_titles = {
		actions: "Azioni",
		created_at: "Creato il",
		email: "Email",
		isAdmin: "Ruolo",
		isBanned: "Status",
		username: "User",
	};
	type Column = (typeof tabledata)[number];

	const columns: ColumnDef<Column>[] = [
		{
			accessorKey: "username",
			cell: ({ row }) => {
				const user = row.original;
				return (
					<Link
						aria-label="Visualizza Utente"
						className="flex items-center gap-2"
						href={`/area-riservata/admin/user-view/edit-user/${user.id}`}
					>
						<UserAvatar
							className="size-8"
							userId={user.id}
							username={user.username}
						/>
						<span className="font-semibold text-sm">{user.username}</span>
					</Link>
				);
			},
			enableHiding: false,
			header: ({ column }) => (
				<DataTableColumnHeader
					column={column}
					title={columns_titles.username}
				/>
			),
		},
		{
			accessorKey: "email",
			header: ({ column }) => (
				<DataTableColumnHeader column={column} title={columns_titles.email} />
			),
		},
		{
			accessorKey: "isAdmin",
			cell: ({ row }) => {
				const isadmin = admin_options.find(
					(status) => status.value === row.getValue("isAdmin"),
				);

				if (!isadmin) {
					return null;
				}

				return (
					<div
						className={cn(
							"flex w-25 items-center",
							isadmin.value === "Admin" && "text-green-500",
						)}
					>
						{isadmin.value === "Admin" && <Crown className="size-4" />}
						<span>{isadmin.label}</span>
					</div>
				);
			},
			filterFn: (row, id, value) => {
				return value.includes(row.getValue(id));
			},
			header: ({ column }) => (
				<DataTableColumnHeader column={column} title={columns_titles.isAdmin} />
			),
		},
		{
			accessorKey: "isBanned",
			filterFn: (row, id, value) => {
				return value.includes(row.getValue(id));
			},
			header: ({ column }) => (
				<DataTableColumnHeader
					column={column}
					title={columns_titles.isBanned}
				/>
			),
		},
		{
			accessorKey: "created_at",
			cell: ({ row }) => {
				const date = row.getValue("created_at");
				return new Date(date as Date).toLocaleDateString();
			},
			enableHiding: false,
			header: ({ column }) => (
				<DataTableColumnHeader
					column={column}
					title={columns_titles.created_at}
				/>
			),
			sortingFn: "datetime",
		},
		{
			accessorKey: "actions",
			cell: ({ row }) => {
				const user = row.original;
				return (
					<DropdownMenu>
						<DropdownMenuTrigger asChild>
							<Button className="size-8 p-0" variant="ghost">
								<span className="sr-only">Apri menu</span>
								<MoreHorizontal className="size-4" />
							</Button>
						</DropdownMenuTrigger>
						<DropdownMenuContent align="end">
							<DropdownMenuLabel>Azioni</DropdownMenuLabel>

							<DropdownMenuItem>
								<Link
									aria-label="Visualizza Ricerca"
									className="flex w-full items-center gap-2"
									href={`/area-riservata/admin/user-view/ricerca/${user.id}`}
								>
									<Search className="text-muted-foreground" /> Ricerca
								</Link>
							</DropdownMenuItem>
							<DropdownMenuItem>
								<Link
									aria-label="Visualizza Comunicazioni"
									className="flex w-full items-center gap-2"
									href={`/area-riservata/admin/user-view/comunicazioni/${user.id}`}
								>
									<Mail className="text-muted-foreground" /> Comunicazioni
								</Link>
							</DropdownMenuItem>
							<DropdownMenuItem>
								<Link
									aria-label="Visualizza Profilo"
									className="flex w-full items-center gap-2"
									href={`/area-riservata/admin/user-view/edit-user/${user.id}`}
								>
									<UserCog className="text-muted-foreground" /> Profilo
								</Link>
							</DropdownMenuItem>

							<DropdownMenuItem>
								<Link
									aria-label="Visualizza Ordini"
									className="flex w-full items-center gap-2"
									href={`/area-riservata/admin/user-view/ordini/${user.id}`}
								>
									<ShoppingBag className="text-muted-foreground" /> Ordini
								</Link>
							</DropdownMenuItem>
							<DropdownMenuItem>
								<Link
									aria-label="Visualizza Allegati"
									className="flex w-full items-center gap-2"
									href={`/area-riservata/admin/user-view/allegati/${user.id}`}
								>
									<Paperclip className="text-muted-foreground" /> Allegati
								</Link>
							</DropdownMenuItem>
							<DropdownMenuSeparator />
							<DropdownMenuItem>
								<Link
									aria-label="Visualizza Chat"
									className={cn(
										"flex w-full items-center gap-2",
										!user.chatid && "text-neutral-200",
									)}
									href={
										user.chatid
											? {
													pathname: "/area-riservata/admin/chats",
													query: { chatId: user.chatid },
												}
											: "/area-riservata/admin/chats"
									}
								>
									<MessagesSquare /> Chat
								</Link>
							</DropdownMenuItem>
							<DropdownMenuSeparator />
							<DropdownMenuItem>
								<button
									aria-label="Login as User"
									className="flex w-full cursor-pointer items-center gap-2"
									onClick={async () => await swap({ id: user.id })}
									type="button"
								>
									<User /> Login
								</button>
							</DropdownMenuItem>
						</DropdownMenuContent>
					</DropdownMenu>
				);
			},
			enableHiding: false,
			enableSorting: false,
			header: ({ column }) => (
				<DataTableColumnHeader column={column} title={columns_titles.actions} />
			),
		},
	];
	const pinnedFiltri: PinnedFiltro[] = [
		{
			columnName: "isAdmin",
			options: [
				{ label: "Admin", value: "Admin" },
				{ label: "Utente", value: "Utente" },
			],
			title: "Ruolo",
		},
		{
			columnName: "isBanned",
			options: [
				{ label: "Bloccato", value: "Bloccato" },
				{ label: "Attivo", value: "Attivo" },
			],
			title: "Status",
		},
	];
	const searchFiltro: SearchFiltro = {
		columnName: "username",
		placeholder: "Filtra utenti...",
	};
	return (
		<div className="mx-auto w-full px-2 py-10">
			<DataTable
				columns={columns}
				columns_titles={columns_titles}
				data={tabledata}
				defaultSort={[{ desc: true, id: "created_at" }]}
				pinnedFiltri={pinnedFiltri}
				searchColumn={searchFiltro}
			/>
		</div>
	);
};
