import { useSuspenseQuery } from "@tanstack/react-query";
import { createFileRoute, redirect } from "@tanstack/react-router";
import { createColumnHelper } from "@tanstack/react-table";
import { format } from "date-fns-tz";
import { Suspense } from "react";
import { Button } from "../../components/ui/button";
import { authClient, useSession } from "../../lib/auth-client";
import { getUsers } from "../../lib/queries/getUsers";
import LstTable from "../../lib/tableStuff/LstTable";
import SearchableHeader from "../../lib/tableStuff/SearchableHeader";
import SkellyTable from "../../lib/tableStuff/SkellyTable";
import { trackLstEvent } from "../../lib/umami.utils";

export const Route = createFileRoute("/admin/users")({
	beforeLoad: async ({ location }) => {
		const { data: session } = await authClient.getSession();
		const allowedRole = ["systemAdmin", "admin"];

		if (!session?.user) {
			throw redirect({
				to: "/",
				search: {
					redirect: location.href,
				},
			});
		}

		if (!allowedRole.includes(session.user.role as string)) {
			throw redirect({
				to: "/",
			});
		}

		return { user: session.user };
	},
	component: RouteComponent,
});

const UserTable = () => {
	const { data } = useSuspenseQuery(getUsers());
	const { data: session } = useSession();

	const columnHelper = createColumnHelper<any>();

	const columns = [
		columnHelper.accessor("name", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Name" searchable={true} />
			),
			filterFn: "includesString",
			cell: (i) => i.getValue(),
		}),
		columnHelper.accessor("email", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Email" searchable={true} />
			),
			filterFn: "includesString",
			cell: (i) => i.getValue(),
		}),
		columnHelper.accessor("role", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Role" searchable={false} />
			),
			filterFn: "includesString",
			cell: (i) => i.getValue(),
		}),
		columnHelper.accessor("updatedAt", {
			header: ({ column }) => (
				<SearchableHeader
					column={column}
					title="Updated at"
					searchable={false}
				/>
			),
			filterFn: "includesString",
			cell: (i) => format(i.getValue(), "M/d/yyyy HH:mm"),
		}),
	];

	if (session && session.user.role === "systemAdmin") {
		columns.push(
			columnHelper.accessor("banned", {
				header: ({ column }) => (
					<SearchableHeader column={column} title="Banned" searchable={false} />
				),
				filterFn: "includesString",
				cell: (i) => <span>{i.getValue() ? "True" : "False"}</span>,
			}),
			columnHelper.accessor("impersonate", {
				header: ({ column }) => (
					<SearchableHeader
						column={column}
						title="Impersonate User"
						searchable={false}
					/>
				),
				filterFn: "includesString",
				cell: (i) => {
					const beSomeone = async () => {
						trackLstEvent("impersonateUser_click", {
							module: "users",
							action: "click",
							label: "impersonating user",
							page: window.location.pathname,
						});

						const { data, error } = await authClient.admin.impersonateUser({
							userId: i.row.original.id, // required
						});

						if (data) {
							await authClient.getSession();
							window.location.replace("/lst/app");
						}

						if (error) {
							console.log(error);
						}
					};

					const cantImpersonate = ["admin", "systemAdmin"];
					if (cantImpersonate.includes(i.row.original.role)) return;
					return <Button onClick={beSomeone}>Become user</Button>;
				},
			}),
		);
	}

	return <LstTable data={data} columns={columns} pageSize={50} />;
};

function RouteComponent() {
	// const createUser = async () => {
	// 	const { data: newUser, error } = await authClient.admin.createUser({
	// 		email: "cowch@gmail.com", // required
	// 		password: "crazypassword", // required
	// 		name: "James Smith", // required
	// 		role: "manager",
	// 	});
	// };

	// const besomeone = async () => {
	// 	const { data, error } = await authClient.admin.impersonateUser({
	// 		userId: "iswCNVzQ9cWulbmsaMbeX6e7fV6Eme6t", // required
	// 	});

	// 	await authClient.getSession();
	// 	window.location.replace("/lst/app");
	// };

	return (
		<Suspense fallback={<SkellyTable />}>
			<UserTable />
		</Suspense>
	);
}
