import type { ColumnDef } from "@tanstack/react-table";
import {
	Crown,
	Mail,
	MessagesSquare,
	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 { UserAvatar } from "~/components/user_avatar";
import { cn } from "~/lib/utils";
import type { Users } from "~/schemas/public/Users";
import { api } from "~/utils/api";
import {
	ContextMenuContent,
	ContextMenuItem,
	ContextMenuSeparator,
} from "../ui/context-menu";

type UserWChatInfo = Pick<
	Users,
	| "id"
	| "username"
	| "email"
	| "telefono"
	| "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 {
			chatid: user.chatid,
			created_at: user.created_at,
			email: user.email,
			telefono: user.telefono,
			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 = {
		created_at: "Creato il",
		email: "Email",
		telefono: "Telefono",
		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: "telefono",
			header: ({ column }) => (
				<DataTableColumnHeader
					column={column}
					title={columns_titles.telefono}
				/>
			),
		},
		{
			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: "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}
				/>
			),
		},
	];
	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}
				contextMenuContent={(data) => (
					<ContextMenuContent>
						<ContextMenuItem>
							<Link
								aria-label="Visualizza Ricerca"
								className="flex w-full items-center gap-2"
								href={`/area-riservata/admin/user-view/ricerca/${data.id}`}
							>
								<Search className="text-muted-foreground" /> Ricerca
							</Link>
						</ContextMenuItem>
						<ContextMenuItem>
							<Link
								aria-label="Visualizza Comunicazioni"
								className="flex w-full items-center gap-2"
								href={`/area-riservata/admin/user-view/comunicazioni/${data.id}`}
							>
								<Mail className="text-muted-foreground" /> Comunicazioni
							</Link>
						</ContextMenuItem>
						<ContextMenuItem>
							<Link
								aria-label="Visualizza Profilo"
								className="flex w-full items-center gap-2"
								href={`/area-riservata/admin/user-view/edit-user/${data.id}`}
							>
								<UserCog className="text-muted-foreground" /> Profilo
							</Link>
						</ContextMenuItem>

						<ContextMenuItem>
							<Link
								aria-label="Visualizza Ordini"
								className="flex w-full items-center gap-2"
								href={`/area-riservata/admin/user-view/ordini/${data.id}`}
							>
								<ShoppingBag className="text-muted-foreground" /> Ordini
							</Link>
						</ContextMenuItem>
						<ContextMenuItem>
							<Link
								aria-label="Visualizza Allegati"
								className="flex w-full items-center gap-2"
								href={`/area-riservata/admin/user-view/allegati/${data.id}`}
							>
								<Paperclip className="text-muted-foreground" /> Allegati
							</Link>
						</ContextMenuItem>
						<ContextMenuSeparator />
						<ContextMenuItem>
							<Link
								aria-label="Visualizza Chat"
								className={cn(
									"flex w-full items-center gap-2",
									!data.chatid && "text-neutral-200",
								)}
								href={
									data.chatid
										? {
												pathname: "/area-riservata/admin/chats",
												query: { chatId: data.chatid },
											}
										: "/area-riservata/admin/chats"
								}
							>
								<MessagesSquare /> Chat
							</Link>
						</ContextMenuItem>
						<ContextMenuSeparator />
						<ContextMenuItem>
							<button
								aria-label="Login as User"
								className="flex w-full cursor-pointer items-center gap-2"
								onClick={async () => await swap({ id: data.id })}
								type="button"
							>
								<User /> Login
							</button>
						</ContextMenuItem>
					</ContextMenuContent>
				)}
				data={tabledata}
				defaultColumnVisibility={{
					actions: true,
					created_at: true,
					email: true,
					telefono: true,
					isAdmin: true,
					isBanned: false,
					username: true,
				}}
				defaultSort={[{ desc: true, id: "created_at" }]}
				pinnedFiltri={pinnedFiltri}
				searchColumn={searchFiltro}
				withContextMenu={true}
			/>
		</div>
	);
};
