<script lang="ts">
	import Icon from "$lib/components/atoms/icon.svelte";
	import Title from "$lib/components/atoms/title.svelte";
	import { Button } from "$lib/components/ui/button";
	import {
		Card,
		CardContent,
		CardHeader,
		CardTitle,
	} from "$lib/components/ui/card";
	import { users } from "$lib/domains/user/data/store";
	import { pageTitle } from "$lib/hooks/page-title.svelte";
	import { trpcApiStore } from "$lib/stores/api";
	import { userInfo } from "$lib/stores/session.info";
	import { onMount } from "svelte";
	import { get } from "svelte/store";
	import type { PageData } from "./$types";
	// Icons
	import OrderIcon from "~icons/solar/box-minimalistic-broken";
	import CheckoutIcon from "~icons/solar/cart-large-minimalistic-broken";
	import CheckIcon from "~icons/solar/check-circle-broken";
	import EyeIcon from "~icons/solar/eye-broken";
	import RefreshIcon from "~icons/solar/refresh-linear";
	import AlertIcon from "~icons/solar/shield-warning-linear";

	pageTitle.set("Dashboard");

	interface Props {
		data: PageData;
	}

	let { data }: Props = $props();

	userInfo.set(data.user);
	users.set(data.users ?? []);

	// Dashboard state
	let isLoading = $state(false); // Start as false since we have server data
	let totalOrders = $state(data?.orders?.total || 0);
	let totalSessions = $state(data?.sessions?.metrics?.total || 0);
	let successfulSessions = $state(data?.sessions?.metrics?.completed || 0);
	let abandonedSessions = $state(data?.sessions?.metrics?.abandoned || 0);

	async function loadDashboardData() {
		isLoading = true;
		const api = get(trpcApiStore);

		if (!api) {
			isLoading = false;
			return;
		}

		try {
			// Load orders data
			const ordersResult = await api.order.getOrdersPaginatedInfo.query({
				info: {
					cursor: undefined,
					limit: 100,
					asc: false,
					totalItemCount: 0,
					totalPages: 0,
					page: 1,
				},
				fetchNext: true,
			});

			totalOrders = ordersResult.data?.totalItemCount || 0;

			// Load all session data
			const historyResult = await api.ckflow.getAllSessionsList.query({
				includeDeleted: false,
			});

			const historySessions = historyResult.data || [];
			totalSessions = historySessions.length;

			// Calculate successful and abandoned sessions
			successfulSessions = historySessions.filter(
				(s) => s.sessionOutcome === "COMPLETED",
			).length;

			abandonedSessions = totalSessions - successfulSessions;
		} catch (error) {
			console.error("Failed to load dashboard data:", error);
		} finally {
			isLoading = false;
		}
	}

	function handleRefresh() {
		loadDashboardData();
	}

	// No need to load dashboard data on mount since we have server data
	// But we can keep the onMount hook in case we need to add more initialization logic later
	onMount(() => {
		// Additional initialization logic can go here if needed
	});
</script>

<main class="grid w-full place-items-center pb-12 md:p-8">
	<div class="mb-4 flex w-full max-w-[90vw] items-center justify-between">
		<Title>Dashboard</Title>
		<Button
			variant="outline"
			size="sm"
			onclick={handleRefresh}
			disabled={isLoading}
		>
			{#if isLoading}
				<span class="mr-2 h-4 w-4 animate-spin">⏳</span>
				Loading...
			{:else}
				<Icon icon={RefreshIcon} cls="mr-2 h-4 w-4" />
				Refresh
			{/if}
		</Button>
	</div>

	<!-- Summary metrics -->
	<div class="grid w-full max-w-[90vw] gap-4 md:grid-cols-4">
		<Card>
			<CardHeader
				class="flex flex-row items-center justify-between space-y-0 pb-2"
			>
				<CardTitle class="text-sm font-medium">Total Orders</CardTitle>
				<Icon icon={OrderIcon} cls="h-4 w-4 text-muted-foreground" />
			</CardHeader>
			<CardContent>
				<div class="text-2xl font-bold">{totalOrders}</div>
				<p class="text-xs text-muted-foreground">
					Lifetime orders placed
				</p>
			</CardContent>
		</Card>

		<Card>
			<CardHeader
				class="flex flex-row items-center justify-between space-y-0 pb-2"
			>
				<CardTitle class="text-sm font-medium">Total Sessions</CardTitle>
				<Icon icon={EyeIcon} cls="h-4 w-4 text-muted-foreground" />
			</CardHeader>
			<CardContent>
				<div class="text-2xl font-bold">{totalSessions}</div>
				<p class="text-xs text-muted-foreground">All checkout sessions</p>
			</CardContent>
		</Card>

		<Card>
			<CardHeader
				class="flex flex-row items-center justify-between space-y-0 pb-2"
			>
				<CardTitle class="text-sm font-medium"
					>Successful Sessions</CardTitle
				>
				<Icon icon={CheckIcon} cls="h-4 w-4 text-muted-foreground" />
			</CardHeader>
			<CardContent>
				<div class="text-2xl font-bold">{successfulSessions}</div>
				<p class="text-xs text-muted-foreground">
					{totalSessions > 0
						? Math.round((successfulSessions / totalSessions) * 100)
						: 0}% of all sessions
				</p>
			</CardContent>
		</Card>

		<Card>
			<CardHeader
				class="flex flex-row items-center justify-between space-y-0 pb-2"
			>
				<CardTitle class="text-sm font-medium"
					>Abandoned Sessions</CardTitle
				>
				<Icon icon={AlertIcon} cls="h-4 w-4 text-muted-foreground" />
			</CardHeader>
			<CardContent>
				<div class="text-2xl font-bold">{abandonedSessions}</div>
				<p class="text-xs text-muted-foreground">
					{totalSessions > 0
						? Math.round((abandonedSessions / totalSessions) * 100)
						: 0}% of all sessions
				</p>
			</CardContent>
		</Card>
	</div>

	<!-- Quick actions -->
	<div class="mt-6 w-full max-w-[90vw]">
		<Card>
			<CardHeader>
				<CardTitle>Quick Actions</CardTitle>
			</CardHeader>
			<CardContent class="grid gap-4 md:grid-cols-3">
				<a
					href="/sessions/live"
					class="flex h-full items-center justify-between rounded-md border p-4 transition-colors hover:bg-accent"
				>
					<div>
						<h3 class="font-medium">Live Sessions</h3>
						<p class="text-sm text-muted-foreground">
							Monitor active checkout flows
						</p>
					</div>
					<Icon
						icon={CheckoutIcon}
						cls="h-5 w-5 text-muted-foreground"
					/>
				</a>

				<a
					href="/orders"
					class="flex h-full items-center justify-between rounded-md border p-4 transition-colors hover:bg-accent"
				>
					<div>
						<h3 class="font-medium">Orders</h3>
						<p class="text-sm text-muted-foreground">
							View and manage orders
						</p>
					</div>
					<Icon icon={OrderIcon} cls="h-5 w-5 text-muted-foreground" />
				</a>

				<a
					href="/sessions/history"
					class="flex h-full items-center justify-between rounded-md border p-4 transition-colors hover:bg-accent"
				>
					<div>
						<h3 class="font-medium">Session History</h3>
						<p class="text-sm text-muted-foreground">
							Analyze past sessions
						</p>
					</div>
					<Icon icon={EyeIcon} cls="h-5 w-5 text-muted-foreground" />
				</a>
			</CardContent>
		</Card>
	</div>
</main>
