<script lang="ts">
	import { goto } from '$app/navigation';
	import { page } from '$app/state';
	import { auth, authInitialized } from '$lib/core/stores/auth';
	import { isUserAdmin } from '$lib/core/admin/adminService';
	import * as Tabs from '$lib/components/ui/tabs/index';
	import Spinner from '$lib/components/ui/spinner/spinner.svelte';
	import { Users, Shield, Settings } from '@lucide/svelte';

	let { children } = $props();

	let loading = $state(true);
	let isAdmin = $state(false);
	let checkedAdmin = $state(false);

	const currentPath = $derived(page.url.pathname);
	const activeTab = $derived(
		currentPath.includes('/admin/roles')
			? 'roles'
			: currentPath.includes('/admin/settings')
				? 'settings'
				: 'users'
	);

	// Wait for Firebase to initialize and check admin status
	$effect(() => {
		const initialized = $authInitialized;
		const currentUser = $auth;

		if (!initialized) {
			// Still waiting for Firebase to check session
			return;
		}

		if (!currentUser) {
			// Firebase initialized but no user
			goto('/login');
			return;
		}

		// User exists, check admin status (only once)
		if (!checkedAdmin) {
			checkedAdmin = true;
			isUserAdmin(currentUser.uid)
				.then((result) => {
					isAdmin = result;
					if (!result) {
						goto('/dashboard');
					} else {
						loading = false;
					}
				})
				.catch((error) => {
					console.error('Error checking admin status:', error);
					goto('/dashboard');
				});
		}
	});

	function handleTabChange(value: string) {
		if (value === 'users') goto('/admin/users');
		else if (value === 'roles') goto('/admin/roles');
		else if (value === 'settings') goto('/admin/settings');
	}
</script>

{#if loading}
	<div class="flex h-full w-full items-center justify-center">
		<Spinner class="size-12" />
	</div>
{:else if isAdmin}
	<div class="flex h-full flex-col overflow-hidden p-4">
		<div class="mb-4">
			<h1 class="text-2xl font-bold">Admin Panel</h1>
			<p class="text-muted-foreground text-sm">Manage users, roles, and system settings</p>
		</div>

		<Tabs.Root value={activeTab} onValueChange={handleTabChange} class="flex flex-1 flex-col overflow-hidden">
			<Tabs.List class="grid w-full max-w-md grid-cols-3">
				<Tabs.Trigger value="users" class="flex items-center gap-2">
					<Users class="h-4 w-4" />
					Users
				</Tabs.Trigger>
				<Tabs.Trigger value="roles" class="flex items-center gap-2">
					<Shield class="h-4 w-4" />
					Roles
				</Tabs.Trigger>
				<Tabs.Trigger value="settings" class="flex items-center gap-2">
					<Settings class="h-4 w-4" />
					Settings
				</Tabs.Trigger>
			</Tabs.List>

			<div class="mt-4 flex-1 overflow-auto">
				{@render children()}
			</div>
		</Tabs.Root>
	</div>
{:else}
	<div class="flex h-full w-full items-center justify-center">
		<p class="text-muted-foreground">Access denied. Admin privileges required.</p>
	</div>
{/if}
