import { createFileRoute, redirect } from "@tanstack/react-router";
import { createColumnHelper } from "@tanstack/react-table";
import { formatInTimeZone } from "date-fns-tz";
//import { useMemo } from "react";
import { useSocketRoom } from "@/hooks/socket.io.hook";
import { authClient } from "@/lib/auth-client";
import { Badge } from "../../components/ui/badge";
import {
	Tooltip,
	TooltipContent,
	TooltipTrigger,
} from "../../components/ui/tooltip";
import LstTable from "../../lib/tableStuff/LstTable";
import SearchableHeader from "../../lib/tableStuff/SearchableHeader";

export const Route = createFileRoute("/admin/logs")({
	beforeLoad: async ({ location }) => {
		const { data: session } = await authClient.getSession();
		const allowedRole = ["admin", "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,
});

interface LogEntry {
	level: number;
	createdAt: Date;
	pid: number;
	hostname: string;
	module: string;
	message?: string;
	[key: string]: any; // catch any extra fields
}

function LevelBadge({ level }: { level: string }) {
	const config: Record<string, { label: string; className: string }> = {
		trace: { label: "TRACE", className: "bg-gray-100 text-gray-600" },
		debug: { label: "DEBUG", className: "bg-blue-50 text-blue-700" },
		info: { label: "INFO", className: "bg-green-50 text-green-700" },
		warn: { label: "WARN", className: "bg-yellow-100 text-yellow-700" },
		error: { label: "ERROR", className: "bg-red-50 text-red-700" },
		fatal: { label: "FATAL", className: "bg-purple-100 text-purple-700" },
	};

	const badge = config[level];

	return (
		<Badge
			className={`rounded px-2 py-0.5 text-xs font-medium ${
				badge?.className ?? "bg-gray-100 text-gray-600"
			}`}
		>
			{badge?.label ?? level}
		</Badge>
	);
}

function RouteComponent() {
	// const logParams = useMemo(() => ({ subModule: "query" }), []);
	// const { data: logs } = useSocketRoom<LogEntry>("logs", logParams);
	const { data: logs } = useSocketRoom<LogEntry>("logs");
	const columnHelper = createColumnHelper<any>();
	const column = [
		columnHelper.accessor("createdAt", {
			header: ({ column }) => <SearchableHeader column={column} title="Time" />,
			filterFn: "includesString",
			cell: (i) =>
				formatInTimeZone(
					i.getValue(),
					`${window.LST_CONFIG?.timezone}`,
					"MM/dd/yyyy HH:mm:ss",
				),
		}),
		columnHelper.accessor("level", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Level" searchable={true} />
			),
			filterFn: "includesString",
			cell: (i) => <LevelBadge level={i.getValue()} />,
		}),
		columnHelper.accessor("module", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Module" />
			),
			filterFn: "includesString",
			cell: (i) => i.getValue(),
		}),
		columnHelper.accessor("subModule", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Submodule" />
			),
			filterFn: "includesString",
			cell: (i) => i.getValue(),
		}),
		columnHelper.accessor("hostname", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Client" />
			),
			filterFn: "includesString",
			cell: (i) => i.getValue(),
		}),
		columnHelper.accessor("message", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Message" />
			),
			filterFn: "includesString",
			cell: (i) => {
				return i.getValue().length > 50 ? (
					<Tooltip>
						<TooltipTrigger>
							<p>{i.getValue().slice(0, 50)}...</p>
						</TooltipTrigger>
						<TooltipContent>
							<p className="text-wrap max-w-48">{i.getValue()}</p>
						</TooltipContent>
					</Tooltip>
				) : (
					i.getValue()
				);
			},
		}),
		columnHelper.accessor("stack", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Stack" />
			),
			filterFn: "includesString",
			cell: (i) => {
				const stack = i.row.original.stack;
				if (!stack) return <span className="text-muted-foreground">—</span>;

				return (
					<Tooltip>
						<TooltipTrigger>
							<p className="max-w-[350px] truncate text-left font-mono text-xs text-muted-foreground hover:text-foreground">
								{stack.length !== 0 ? "Hover to see stack error" : "-"}
							</p>
						</TooltipTrigger>
						<TooltipContent
							side="left"
							align="start"
							className="max-w-[900px] bg-zinc-950 text-zinc-50"
						>
							<pre className="max-h-[500px] overflow-auto whitespace-pre-wrap rounded-md p-3 text-xs leading-relaxed">
								<code>{JSON.stringify(stack, null, 2)}</code>
							</pre>
						</TooltipContent>
					</Tooltip>
				);
			},
		}),
	];
	return (
		// <div>
		// 	{/* Log Table */}
		// 	<div className="rounded border overflow-auto max-h-[600px]">
		// 		<table className="w-full text-sm">
		// 			<thead className="bg-muted sticky top-0">
		// 				<tr>
		// 					<th className="text-left px-3 py-2">Time</th>
		// 					<th className="text-left px-3 py-2">Level</th>
		// 					<th className="text-left px-3 py-2">Module</th>
		// 					<th className="text-left px-3 py-2">Host</th>
		// 					<th className="text-left px-3 py-2">Message</th>
		// 				</tr>
		// 			</thead>
		// 			<tbody>
		// 				{logs.length === 0 ? (
		// 					<tr>
		// 						<td
		// 							colSpan={6}
		// 							className="text-center py-6 text-muted-foreground"
		// 						>
		// 							{logsInfo}
		// 						</td>
		// 					</tr>
		// 				) : (
		// 					logs.map((log, i) => (
		// 						<tr
		// 							key={`${log.id}-${i}`}
		// 							className="border-t hover:bg-muted/50"
		// 						>
		// 							<td className="px-3 py-2 whitespace-nowrap">
		// 								{new Date(log.createdAt).toLocaleTimeString()}
		// 							</td>
		// 							<td className="px-3 py-2">
		// 								<LevelBadge level={log.level} />
		// 							</td>
		// 							<td className="px-3 py-2">{log.module}</td>
		// 							<td className="px-3 py-2">{log.hostname}</td>
		// 							<td className="px-3 py-2 max-w-sm truncate">{log.message}</td>
		// 						</tr>
		// 					))
		// 				)}
		// 			</tbody>
		// 		</table>
		// 	</div>
		// </div>
		<LstTable data={logs} columns={column} pageSize={50} />
	);
}
