<script lang="ts">
	import Icon from "$lib/components/atoms/icon.svelte";
	import { Button } from "$lib/components/ui/button";
	import * as Card from "$lib/components/ui/card";
	import { cn } from "$lib/utils";
	import {
		Clock,
		Globe,
		Laptop,
		Loader2,
		LogOut,
		Smartphone,
	} from "@lucide/svelte";
	import { onMount } from "svelte";
	import { sessionsVM } from "./sessions.vm.svelte";

	onMount(() => {
		setTimeout(() => {
			sessionsVM.fetchActiveSessions();
		}, 500);
	});

	function getDeviceIcon(userAgent: string | undefined | null) {
		if (!userAgent) {
			return Globe;
		}
		if (
			userAgent.toLowerCase().includes("mobile") ||
			userAgent.toLowerCase().includes("android") ||
			userAgent.toLowerCase().includes("iphone")
		) {
			return Smartphone;
		}
		return Laptop;
	}

	function extractInfoFromUA(userAgent: string) {
		const osRegex = /(iPhone|iPad|Macintosh|Windows|Android)/;
		const browserRegex = /(Chrome|Safari|Firefox|Opera|Edge|Trident)/;

		const osMatch = userAgent.match(osRegex);
		const browserMatch = userAgent.match(browserRegex);

		const defBro = "Unknown Browser";
		const defOS = "Unknown OS";

		if (osMatch && osMatch.length > 0) {
			return {
				os: osMatch[0] || defOS,
				browser: browserMatch ? browserMatch[0] || defBro : defBro,
			};
		} else {
			return { os: defOS, browser: defBro };
		}
	}
</script>

<Card.Root>
	<Card.Header>
		<div class="flex items-center gap-2">
			<Icon icon={Globe} cls="h-5 w-5 text-primary" />
			<Card.Title>Active Sessions</Card.Title>
		</div>
		<Card.Description>
			Manage and monitor your active login sessions across devices.
		</Card.Description>
	</Card.Header>
	<Card.Content>
		<div class="space-y-6">
			{#if sessionsVM.isLoading && sessionsVM.activeSessions.length === 0}
				<div class="flex justify-center py-6">
					<Icon
						icon={Loader2}
						cls="h-8 w-8 animate-spin text-muted-foreground"
					/>
				</div>
			{:else if sessionsVM.activeSessions.length > 0}
				<div class="space-y-4">
					{#each sessionsVM.activeSessions as session}
						{@const { os, browser } = extractInfoFromUA(
							session.userAgent ?? "",
						)}
						<div
							class={cn(
								"flex flex-col gap-3 rounded-md border p-4 shadow-sm",
								session.isCurrent && "bg-primary/10",
							)}
						>
							<div class="flex items-center gap-3">
								<div class="bg-primary/10 rounded-full p-2">
									<Icon
										icon={getDeviceIcon(session.userAgent)}
										cls="h-5 w-5 text-primary"
									/>
								</div>
								<div>
									<div class="flex items-center gap-2">
										<h4 class="font-medium">
											{browser || "Unknown Browser"}
											on
											{os || "Unknown OS"}
										</h4>
										{#if session.isCurrent}
											<span
												class="bg-primary/10 text-primary rounded-full px-2 py-0.5 text-xs font-medium"
											>
												Current Session
											</span>
										{/if}
									</div>
									<div class="text-muted-foreground text-sm">
										{session.ipAddress || "Unknown IP"}
									</div>
									<div
										class="text-muted-foreground flex items-center gap-1 text-xs"
									>
										<Icon icon={Clock} cls="h-3 w-3" />
										<span>
											Created{" "}
											{sessionsVM.formatRelativeTime(
												session.createdAt.getTime(),
											)}
										</span>
									</div>
								</div>
							</div>
							{#if !session.isCurrent}
								<Button
									variant="outline"
									size="sm"
									class="self-end"
									onclick={() =>
										sessionsVM.terminateSession(session.id)}
									disabled={sessionsVM.isLoading}
								>
									{#if sessionsVM.isLoading}
										<Icon
											icon={Loader2}
											cls="mr-2 h-4 w-4 animate-spin"
										/>
									{:else}
										<Icon
											icon={LogOut}
											cls="mr-2 h-4 w-4 text-destructive"
										/>
										End Session
									{/if}
								</Button>
							{/if}
						</div>
					{/each}
				</div>

				{#if sessionsVM.activeSessions.filter((s) => !s.isCurrent).length > 0}
					<Button
						variant="outline"
						class="w-full"
						onclick={() => sessionsVM.terminateAllOtherSessions()}
						disabled={sessionsVM.isLoading}
					>
						{#if sessionsVM.isLoading}
							<Icon
								icon={Loader2}
								cls="mr-2 h-4 w-4 animate-spin"
							/>
						{:else}
							<Icon icon={LogOut} cls="h-4 w-4 mr-2" />
							Sign out of all other sessions
						{/if}
					</Button>
				{/if}
			{:else}
				<div class="p-6 text-center">
					<p class="text-muted-foreground">
						No active sessions found. This is unusual and might
						indicate a problem.
					</p>
				</div>
			{/if}
		</div>
	</Card.Content>
</Card.Root>
