<script lang="ts">
	import { Button } from '$lib/components/ui/button';
	import { ThemeToggle } from '$lib/components/ui/theme-toggle';
	import { LanguageToggle } from '$lib/components/ui/language-toggle';
	import ThemePicker from '$lib/components/ui/theme-picker.svelte';
	import ColorPicker from '$lib/components/ui/ColorPicker.svelte';
	import { signOut } from '@auth/sveltekit/client';
	import { languageStore } from '$lib/stores/language.svelte';
	import { enhance } from '$app/forms';

	let {
		userName,
		userEmail,
		dashboardTheme = 'none',
		dashboardColor = null,
		isAuthenticated = false,
		onThemeUpdate,
		onColorUpdate
	}: {
		userName?: string | null;
		userEmail?: string | null;
		dashboardTheme?: string;
		dashboardColor?: string | null;
		isAuthenticated?: boolean;
		onThemeUpdate?: (theme: string | null) => void;
		onColorUpdate?: (color: string | null) => void;
	} = $props();

	const t = $derived(languageStore.t);

	async function handleThemeChange(theme: string) {
		if (onThemeUpdate) {
			onThemeUpdate(theme);
		}

		if (isAuthenticated) {
			const formData = new FormData();
			formData.append('theme', theme);

			await fetch('?/updateDashboardTheme', {
				method: 'POST',
				body: formData
			});
		}
	}

	let localColor = $state(dashboardColor);

	$effect(() => {
		localColor = dashboardColor;
	});

	async function handleColorChange() {
		if (onColorUpdate) {
			onColorUpdate(localColor);
		}

		if (isAuthenticated) {
			const formData = new FormData();
			if (localColor) {
				formData.append('color', localColor);
			}

			await fetch('?/updateDashboardColor', {
				method: 'POST',
				body: formData
			});
		}
	}
</script>

<div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
	<div class="flex-1 min-w-0">
		<h1 class="text-3xl font-bold">{t.nav.dashboard}</h1>
		{#if isAuthenticated}
			<p class="text-muted-foreground truncate">{t.dashboard.welcomeBack}, {userName || userEmail}</p>
		{:else}
			<p class="text-muted-foreground">{t.dashboard.anonymousDashboard || "Your local wishlists"}</p>
		{/if}
	</div>
	<div class="flex items-center gap-1 sm:gap-2 flex-shrink-0">
		<ColorPicker bind:color={localColor} onchange={handleColorChange} />
		<ThemePicker value={dashboardTheme} onValueChange={handleThemeChange} />
		<LanguageToggle />
		<ThemeToggle />
		{#if isAuthenticated}
			<Button variant="outline" onclick={() => signOut({ callbackUrl: '/' })}>{t.auth.signOut}</Button>
		{:else}
			<Button variant="outline" onclick={() => (window.location.href = '/signin')}>{t.auth.signIn}</Button>
		{/if}
	</div>
</div>
