<script lang="ts">
	import * as Sidebar from '$lib/components/ui/sidebar/index.js';
	import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';

	import { useSidebar } from '$lib/components/ui/sidebar/index';
	import { ChevronsUpDownIcon, PlusIcon, LogOutIcon } from '@lucide/svelte/icons';
	import { auth as authStore } from '$lib/core/stores/auth';
	import { get } from 'svelte/store';
	import type { User } from 'firebase/auth';
	import { asset } from '$app/paths';
	import { auth } from '$lib/core/client/firebase';
	import { goto } from '$app/navigation';
	import { onDestroy } from 'svelte';
	import * as adb from '$lib/core/adb/adb';
	import { browser } from '$app/environment';
	import { deleteCookiesOnNonBrowser } from '$lib/helpers/cookie';
	import { socketStore } from '$lib/core/stores/websocketStore';

	const sidebar = useSidebar();

	let currentUser: User | null = $state(null);
	let userImage: any = $state(null);

	let unsubAuthStore = authStore.subscribe((user) => {
		if (user) {
			currentUser = user;
			userImage = asset(currentUser?.photoURL ?? '');
		}
	});

	onDestroy(() => {
		unsubAuthStore();
	});

	async function logout() {
		let instance = adb.getAdbInstance();
		if (instance) {
			try {
				await adb.executeCmd('rm /sdcard/coffeevending/ignore_pass');
				await adb.executeCmd('reboot');
				await adb.disconnect();
			} catch (e) {
				console.error('error disconnect device while logging out', e);
			}
		}

		authStore.set(null);

		let socket = get(socketStore);
		if (socket) {
			socket.close(1000, 'logout');
		}

		socketStore.set(null);
		if (browser && 'cookieStore' in window) await cookieStore.delete('logged_in');
		else deleteCookiesOnNonBrowser('logged_in');
		await auth.signOut();
		await auth.updateCurrentUser(null);
		goto('/login');
	}
</script>

<Sidebar.Menu>
	<Sidebar.MenuItem>
		<DropdownMenu.Root>
			<DropdownMenu.Trigger>
				{#snippet child({ props })}
					<Sidebar.MenuButton
						{...props}
						size="lg"
						class="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
					>
						<div
							class="flex aspect-square size-8 items-center justify-center rounded-lg bg-sidebar-primary text-sidebar-primary-foreground"
						>
							<!-- <activeTeam.logo class="size-4" /> -->
							<img src={userImage} alt="" loading="lazy" />
						</div>
						<div class="grid flex-1 text-start text-sm leading-tight">
							<span class="truncate font-medium">
								{currentUser?.displayName}
							</span>
							<span class="truncate text-xs">{currentUser?.email}</span>
						</div>
						<ChevronsUpDownIcon class="ms-auto" />
					</Sidebar.MenuButton>
				{/snippet}
			</DropdownMenu.Trigger>
			<DropdownMenu.Content
				class="w-(--bits-dropdown-menu-anchor-width) min-w-56 rounded-lg"
				align="start"
				side={sidebar.isMobile ? 'bottom' : 'right'}
				sideOffset={4}
			>
				<DropdownMenu.Label class="text-xs text-muted-foreground">Account</DropdownMenu.Label>
				<!-- {#each teams as team, index (team.name)}
                <DropdownMenu.Item onSelect={() => (activeTeam = team)} class="gap-2 p-2">
                    <div class="flex size-6 items-center justify-center rounded-md border">
                    <team.logo class="size-3.5 shrink-0" />
                    </div>
                    {team.name}
                    <DropdownMenu.Shortcut>⌘{index + 1}</DropdownMenu.Shortcut>
                </DropdownMenu.Item>
                {/each} -->
				<DropdownMenu.Separator />
				<DropdownMenu.Item class="gap-2 p-2" onclick={logout}>
					<div class="flex size-6 items-center justify-center rounded-md border bg-transparent">
						<LogOutIcon class="size-4" />
					</div>
					<div class="font-medium text-muted-foreground">
						<button onclick={logout}> Logout </button>
					</div>
				</DropdownMenu.Item>
			</DropdownMenu.Content>
		</DropdownMenu.Root>
	</Sidebar.MenuItem>
</Sidebar.Menu>
