import { useMutation, useSuspenseQuery } from "@tanstack/react-query";
import { createFileRoute, redirect } from "@tanstack/react-router";
import { createColumnHelper } from "@tanstack/react-table";
import { Suspense, useMemo } from "react";
import { toast } from "sonner";

import {
	Card,
	CardContent,
	CardHeader,
	CardTitle,
} from "../../components/ui/card";

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 { getSettings } from "../../lib/queries/getSettings";
import EditableCellInput from "../../lib/tableStuff/EditableCellInput";
import LstTable from "../../lib/tableStuff/LstTable";
import SearchableHeader from "../../lib/tableStuff/SearchableHeader";
import SkellyTable from "../../lib/tableStuff/SkellyTable";
import FeatureSettings from "./-components/FeatureSettings";

type Settings = {
	settings_id: string;
	name: string;
	active: boolean;
	value: string;
	description: string;
	moduleName: string;
	roles: string[];
};

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

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

		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,
});

function SettingsTableCard() {
	const { data, refetch } = useSuspenseQuery(getSettings());
	const columnHelper = createColumnHelper<Settings>();

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

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

	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("value", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Value" />
			),

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

	const { standardSettings, featureSettings, systemSetting } = useMemo(() => {
		return {
			standardSettings: data.filter(
				(setting: any) => setting.settingType === "standard",
			),
			featureSettings: data.filter(
				(setting: any) => setting.settingType === "feature",
			),
			systemSetting: data.filter(
				(setting: any) => setting.settingType === "system",
			),
		};
	}, [data]);
	return (
		<>
			<TabsContent value="feature">
				<FeatureSettings data={featureSettings} />
			</TabsContent>
			<TabsContent value="system">
				<LstTable data={systemSetting} columns={column} />
			</TabsContent>
			<TabsContent value="standard">
				<LstTable data={standardSettings} columns={column} />
			</TabsContent>
		</>
	);
}

function RouteComponent() {
	return (
		<div className="space-y-6 w-7xl flex flex-col justify-center">
			<div className="space-y-2">
				<h1 className="text-2xl font-semibold text-center">Settings</h1>
				<p className="text-sm text-muted-foreground text-center">
					Manage your settings and related data.
				</p>
			</div>

			<Card>
				<CardHeader>
					<CardTitle>System Settings</CardTitle>
				</CardHeader>
				<CardContent>
					<Tabs defaultValue="standard" className="w-full">
						<TabsList>
							<TabsTrigger value="feature">Features</TabsTrigger>
							<TabsTrigger value="system">System</TabsTrigger>
							<TabsTrigger value="standard">Standard</TabsTrigger>
						</TabsList>
						<Suspense fallback={<SkellyTable />}>
							<SettingsTableCard />
						</Suspense>
					</Tabs>
				</CardContent>
			</Card>
		</div>
	);
}
