"use client";

import { LogOut } from "lucide-react";
import NextLink from "next/link";
import { useEffect } from "react";
import { authClient } from "../lib/auth-client";
import { SharedBackButton } from "./shared-back-button";
import { SessionOrganizationSwitcher } from "./organization/session-organization-switcher";
import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
import {
	Card,
	CardContent,
	CardDescription,
	CardHeader,
	CardTitle,
} from "./ui/card";
import { Snippet } from "./ui/snippet";

export function SessionPanel() {
	const { data, isPending, error, refetch } = authClient.useSession();
	const sessionRecord = (data?.session ?? {}) as unknown as Record<
		string,
		unknown
	>;
	const userRecord = (data?.user ?? {}) as unknown as Record<string, unknown>;
	const activeOrganizationValue =
		sessionRecord.activeOrganizationId ??
		sessionRecord.active_organization_id ??
		sessionRecord.organization_id ??
		sessionRecord.organizationId;
	const activeOrganizationId =
		typeof activeOrganizationValue === "string"
			? activeOrganizationValue
			: null;

	const copyableEntries = [
		{ label: "session_token", value: sessionRecord.token },
		{ label: "session_id", value: sessionRecord.id },
		{
			label: "active_organization_id",
			value:
				activeOrganizationValue ??
				userRecord.activeOrganizationId ??
				userRecord.active_organization_id ??
				userRecord.organization_id ??
				userRecord.organizationId,
		},
		{
			label: "session_user_id",
			value: sessionRecord.user_id ?? sessionRecord.userId,
		},
		{ label: "user_id", value: userRecord.id },
		{ label: "email", value: userRecord.email },
	].filter(
		(entry): entry is { label: string; value: string } =>
			typeof entry.value === "string" && entry.value.length > 0,
	);

	const signOut = async () => {
		await authClient.signOut();
		await refetch();
	};

	useEffect(() => {
		const onVisible = () => {
			if (!document.hidden) {
				void refetch();
			}
		};
		const interval = window.setInterval(() => {
			void refetch();
		}, 30000);
		document.addEventListener("visibilitychange", onVisible);
		return () => {
			window.clearInterval(interval);
			document.removeEventListener("visibilitychange", onVisible);
		};
	}, [refetch]);

	return (
		<main className="mx-auto w-full max-w-6xl px-4 pb-10 pt-8">
			<div className="mb-4 flex items-center justify-between gap-3">
				<SharedBackButton fallbackHref="/login" />
				<Badge variant="secondary">Session inspector</Badge>
			</div>

			<Card>
				<CardHeader>
					<CardTitle>Current session</CardTitle>
					<CardDescription>
						Live session state fetched with Better Auth SDK.
					</CardDescription>
				</CardHeader>
				<CardContent className="grid gap-4">
					<div className="flex flex-wrap gap-2 text-xs">
						<Badge
							variant={
								isPending
									? "secondary"
									: error
										? "destructive"
										: data
											? "success"
											: "warning"
							}
						>
							status:{" "}
							{isPending
								? "loading"
								: error
									? "error"
									: data
										? "authenticated"
										: "unauthenticated"}
						</Badge>
						<Badge variant={data?.session?.token ? "success" : "warning"}>
							token: {data?.session?.token ? "present" : "none"}
						</Badge>
						<Badge variant={data?.user?.email ? "success" : "warning"}>
							user: {data?.user?.email ?? "none"}
						</Badge>
						<Badge variant="secondary">auto refresh: 30s + focus</Badge>
					</div>

					{isPending ? (
						<p className="text-sm text-slate-500">Loading session...</p>
					) : null}
					{error ? (
						<p className="rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
							Error: {error.message}
						</p>
					) : null}

					<section className="rounded-xl border border-slate-200 bg-white p-4">
						<h3 className="text-sm font-semibold text-slate-900">
							Copyable session fields
						</h3>
						<p className="mt-1 text-xs text-slate-500">
							Click the icon on the right to copy exact values.
						</p>
						<div className="mt-3 grid gap-3 md:grid-cols-2">
							{copyableEntries.length > 0 ? (
								copyableEntries.map((entry) => (
									<div key={entry.label} className="grid gap-1">
										<span className="text-xs font-medium text-slate-600">
											{entry.label}
										</span>
										<Snippet text={entry.value} prompt={false} />
									</div>
								))
							) : (
								<p className="text-xs text-slate-500">
									No copyable fields returned yet.
								</p>
							)}
						</div>
					</section>

					<SessionOrganizationSwitcher
						activeOrganizationId={activeOrganizationId}
						onSessionRefresh={async () => {
							await refetch();
						}}
					/>

					<pre className="max-h-[420px] overflow-auto rounded-xl border border-slate-200 bg-slate-950 p-4 text-xs text-slate-100">
						{JSON.stringify(data, null, 2)}
					</pre>

					<div className="flex flex-wrap gap-2">
						<Button variant="destructive" onClick={signOut}>
							<LogOut className="mr-2 h-4 w-4" />
							Sign out
						</Button>
						<Button variant="outline" asChild>
							<NextLink href="/my-emails">My emails</NextLink>
						</Button>
						<Button variant="outline" asChild>
							<NextLink href="/admin/emails">Admin emails</NextLink>
						</Button>
						<Button variant="outline" asChild>
							<NextLink href="/session/activity">Session activity</NextLink>
						</Button>
						<Button variant="outline" asChild>
							<NextLink href="/schema-debug">Schema debug</NextLink>
						</Button>
						<Button variant="outline" asChild>
							<NextLink href="/organizations">Organizations</NextLink>
						</Button>
						<Button variant="outline" asChild>
							<NextLink href="/settings">Settings dialog</NextLink>
						</Button>
					</div>
				</CardContent>
			</Card>
		</main>
	);
}
