import { useMutation, useSuspenseQuery } from "@tanstack/react-query";
import { createFileRoute, redirect } from "@tanstack/react-router";
import { createColumnHelper } from "@tanstack/react-table";
import axios from "axios";
import { Trash } from "lucide-react";
import { Suspense, useState } from "react";
import { toast } from "sonner";
import type { Notifications } from "../../../types/notifications";
import { Button } from "../../components/ui/button";
import { Card, CardContent } from "../../components/ui/card";
import { Label } from "../../components/ui/label";
import { Switch } from "../../components/ui/switch";
import {
	Tabs,
	TabsContent,
	TabsList,
	TabsTrigger,
} from "../../components/ui/tabs";
import {
	Tooltip,
	TooltipContent,
	TooltipTrigger,
} from "../../components/ui/tooltip";
import { api } from "../../lib/apiHelper";
import { authClient } from "../../lib/auth-client";
import { notificationSubs } from "../../lib/queries/notificationSubs";
import { notifications } from "../../lib/queries/notifications";
import EditableCellInput from "../../lib/tableStuff/EditableCellInput";
import LstTable from "../../lib/tableStuff/LstTable";
import SearchableHeader from "../../lib/tableStuff/SearchableHeader";
import SkellyTable from "../../lib/tableStuff/SkellyTable";

const updateNotifications = async (
	id: string,
	data: Record<string, string | number | boolean | null>,
) => {
	//console.log(id, data);
	try {
		const res = await axios.patch(
			`/notification/${id}`,
			{ interval: data.interval },
			{
				withCredentials: true,
			},
		);
		toast.success(`Notification was just updated`);
		return res;
	} catch (err) {
		toast.error("Error in updating the settings");
		return err;
	}
};

export const Route = createFileRoute("/admin/notifications")({
	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 NotificationTable = () => {
	const { data, refetch } = useSuspenseQuery(notifications());
	const { data: subs, refetch: subRefetch } = useSuspenseQuery(
		notificationSubs(),
	);
	const columnHelper = createColumnHelper<Notifications>();

	const notificationMap = Object.fromEntries(data.map((n: any) => [n.id, n]));

	const subData = subs.map((sub: any) => ({
		...sub,
		name: notificationMap[sub.notificationId].name || null,
		description: notificationMap[sub.notificationId].description || null,
		emails: sub.emails ? sub.emails.join(",") : null,
	}));

	const updateNotification = useMutation({
		mutationFn: ({
			id,
			field,
			value,
		}: {
			id: string;
			field: string;
			value: string | number | boolean | null;
		}) => updateNotifications(id, { [field]: value }),

		onSuccess: () => {
			// refetch or update cache
			refetch();
		},
	});

	const removeNotification = async (ns: any) => {
		try {
			const res = await api.delete(`/notification/sub`, {
				withCredentials: true,
				data: {
					userId: ns.userId,
					notificationId: ns.notificationId,
				},
			});

			if (res.data.success) {
				toast.success(`Subscription removed`);
				subRefetch();
			} else {
				console.info(res);
				toast.error(res.data.message);
			}
		} catch {
			toast.error(`There was an error removing subscription.`);
		}
	};

	const column = [
		columnHelper.accessor("name", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Name" searchable={true} />
			),
			filterFn: "includesString",
			cell: (i) => i.getValue(),
		}),
		columnHelper.accessor("description", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Description" />
			),
			cell: (i) => (
				<Tooltip>
					<TooltipTrigger>
						{i.getValue()?.length > 25 ? (
							<span>{i.getValue().slice(0, 25)}...</span>
						) : (
							<span>{i.getValue()}</span>
						)}
					</TooltipTrigger>
					<TooltipContent>{i.getValue()}</TooltipContent>
				</Tooltip>
			),
		}),
		columnHelper.accessor("active", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Active" searchable={false} />
			),
			filterFn: "includesString",
			cell: (i) => {
				// biome-ignore lint: just removing the lint for now to get this going will maybe fix later
				const [activeToggle, setActiveToggle] = useState(i.getValue());

				const onToggle = async (e: boolean) => {
					setActiveToggle(e);

					try {
						const res = await api.patch(
							`/notification/${i.row.original.id}`,
							{
								active: !activeToggle,
							},
							
						);

						if (res.data.success) {
							toast.success(
								`${i.row.original.name} was set to ${activeToggle ? "Inactive" : "Active"}`,
							);
							refetch();
						}
					} catch (error) {
						console.error(error);
					}
				};

				return (
					<div className="w-48">
						<div className="flex items-center space-x-2">
							<Switch
								id={i.row.original.id}
								checked={activeToggle}
								onCheckedChange={(e) => onToggle(e)}
								//onBlur={field.handleBlur}
							/>
							<Label htmlFor={i.row.original.id}>
								{activeToggle ? "Active" : "Deactivated"}
							</Label>
						</div>
					</div>
				);
			},
		}),
		columnHelper.accessor("interval", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Interval" />
			),

			filterFn: "includesString",
			cell: ({ row, getValue }) => {
				return (
					<EditableCellInput
						value={getValue()}
						id={row.original.id}
						field="interval"
						onSubmit={({ id, field, value }) => {
							updateNotification.mutate({ id, field, value });
						}}
					/>
				);
			},
		}),
	];

	const subsColumn = [
		columnHelper.accessor("name", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Name" searchable={true} />
			),
			filterFn: "includesString",
			cell: (i) => i.getValue(),
		}),
		columnHelper.accessor("description", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Description" />
			),
			cell: (i) => (
				<Tooltip>
					<TooltipTrigger>
						{i.getValue()?.length > 25 ? (
							<span>{i.getValue().slice(0, 25)}...</span>
						) : (
							<span>{i.getValue()}</span>
						)}
					</TooltipTrigger>
					<TooltipContent>{i.getValue()}</TooltipContent>
				</Tooltip>
			),
		}),
		columnHelper.accessor("emails", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Emails" searchable={true} />
			),
			filterFn: "includesString",
			cell: (i) => i.getValue(),
		}),
		columnHelper.accessor("remove", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Remove" searchable={false} />
			),
			filterFn: "includesString",
			cell: (i) => {
				return (
					<Button
						size="icon"
						variant={"destructive"}
						onClick={() => removeNotification(i.row.original)}
					>
						<Trash />
					</Button>
				);
			},
		}),
	];

	return (
		<>
			<TabsContent value="notifications">
				<LstTable data={data} columns={column} />
			</TabsContent>
			<TabsContent value="subscriptions">
				<LstTable data={subData} columns={subsColumn} />
			</TabsContent>
		</>
	);
};

function RouteComponent() {
	return (
		<div className="space-y-6">
			<div className="space-y-2">
				<h1 className="text-2xl font-semibold">Notifications</h1>
				<p className="text-sm text-muted-foreground">
					Manage all notification settings and user subs.
				</p>
			</div>

			<Card>
				<CardContent>
					<Tabs defaultValue="notifications" className="w-full">
						<TabsList>
							<TabsTrigger value="notifications">Notifications</TabsTrigger>
							<TabsTrigger value="subscriptions">Subscriptions</TabsTrigger>
						</TabsList>
						<Suspense fallback={<SkellyTable />}>
							<NotificationTable />
						</Suspense>
					</Tabs>
				</CardContent>
			</Card>
		</div>
	);
}
