<script lang="ts">
	import { enhance } from '$app/forms';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '$lib/components/ui/card';
	import { Avatar, AvatarFallback, AvatarImage } from '$lib/components/ui/avatar';
	import { resolveUserAvatarUrl } from '$lib/utils';
	import type { PageData, ActionData } from './$types';

	let { data, form }: { data: PageData; form: ActionData } = $props();

	// State derivado de los datos del servidor
	let profile = $derived(data.profile);
	let serverError = $derived(data.error);

	// State local
	let saving = $state(false);
	let success = $state('');
	let error = $state('');
	let avatarLoadFailed = $state(false);

	// Effect para manejar errores del servidor
	$effect(() => {
		if (serverError) {
			error = serverError;
		}
	});

	// Effect para manejar respuesta del form action
	$effect(() => {
		if (form?.success) {
			success = 'Perfil actualizado exitosamente';
			setTimeout(() => {
				success = '';
			}, 3000);
		}
		
		if (form?.error) {
			error = form.error;
		}
	});

	function getInitials(profile: typeof data.profile): string {
		if (!profile) return '??';
		const first = profile.first_name?.[0] || '';
		const last = profile.last_name?.[0] || '';
		return (first + last).toUpperCase() || profile.username?.[0]?.toUpperCase() || '?';
	}

	function handleAvatarError() {
		avatarLoadFailed = true;
	}

	let currentAvatarUrl = $derived(
		avatarLoadFailed ? '' : resolveUserAvatarUrl(profile?.workspace_avatar_url, profile?.legacy_avatar_url || profile?.avatar_url)
	);
</script>

<div class="container mx-auto py-8 px-4 max-w-5xl">
	<div class="mb-8 space-y-1">
		<h1 class="text-4xl font-bold tracking-tight">Configuración de Cuenta</h1>
		<p class="text-muted-foreground text-lg">
			Gestiona tu información personal y preferencias
		</p>
	</div>

	{#if !profile && serverError}
		<Card>
			<CardContent class="py-12">
				<div class="text-center text-destructive">
					<p class="font-medium">{serverError}</p>
					<Button class="mt-4" onclick={() => window.location.reload()}>
						Reintentar
					</Button>
				</div>
			</CardContent>
		</Card>
	{:else if profile}
		<form 
			method="POST" 
			action="?/updateProfile"
			enctype="multipart/form-data"
			use:enhance={({ formData }) => {				
							
				saving = true;
				error = '';
				success = '';
				return async ({ update }) => {
					// reset:false evita que SvelteKit limpie el formulario nativo.
					// update() ya llama a invalidateAll internamente.
					await update({ reset: false });
					saving = false;
				};
			}}
		>
			<div class="space-y-6 pb-24">
				<!-- Profile Picture -->
				<Card class="transition-shadow hover:shadow-md">
				<CardHeader>
					<CardTitle class="text-xl">Foto de Perfil</CardTitle>
					<CardDescription>Esta imagen se administra desde Workspace</CardDescription>
				</CardHeader>
				<CardContent class="space-y-6">
					<div class="flex flex-col sm:flex-row items-center gap-8">
						<div class="relative group">
								<Avatar class="h-28 w-28 ring-4 ring-background shadow-lg transition-all group-hover:scale-105 group-hover:ring-primary/50">
									<AvatarImage src={currentAvatarUrl} alt={profile.username} onerror={handleAvatarError} />
									<AvatarFallback class="text-3xl font-semibold">{getInitials(profile)}</AvatarFallback>
								</Avatar>
								<div class="absolute inset-0 rounded-full bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
									<svg class="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
										<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
									</svg>
								</div>
						</div>
						
						<div class="flex-1 w-full">
							<p class="text-sm text-muted-foreground">
								La foto de perfil se sincroniza desde Workspace en login, refresh de sesión y carga de perfil.
							</p>
							<p class="text-sm text-muted-foreground">
								Para cambiarla, actualízala en Workspace y vuelve a iniciar sesión.
							</p>
						</div>
					</div>
				</CardContent>
			</Card>

			<!-- Personal Information -->
			<Card class="transition-shadow hover:shadow-md">
				<CardHeader>
					<CardTitle class="text-xl">Información Personal</CardTitle>
					<CardDescription>Actualiza tus datos personales</CardDescription>
				</CardHeader>
				<CardContent class="space-y-6">
					<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
						<div class="space-y-2.5">
							<Label for="first_name" class="text-sm font-medium">Nombre</Label>
							<Input
								id="first_name"
								name="first_name"
								value={profile.first_name || ''}
								placeholder="Tu nombre"
								class="transition-colors"
								required
							/>
						</div>

						<div class="space-y-2.5">
							<Label for="last_name" class="text-sm font-medium">Apellido</Label>
							<Input
								id="last_name"
								name="last_name"
								value={profile.last_name || ''}
								placeholder="Tu apellido"
								class="transition-colors"
								required
							/>
						</div>
					</div>

					<div class="space-y-2.5">
						<Label for="phone" class="text-sm font-medium">Teléfono</Label>
						<Input
							id="phone"
							name="phone"
							type="tel"
							value={profile.phone || ''}
							placeholder="+52 123 456 7890"
							class="transition-colors"
						/>
					</div>
				</CardContent>
			</Card>

			<!-- Account Information (Read-only) -->
			<Card class="transition-shadow hover:shadow-md">
				<CardHeader>
					<CardTitle class="text-xl">Información de Cuenta</CardTitle>
					<CardDescription>Datos de tu cuenta en el sistema</CardDescription>
				</CardHeader>
				<CardContent class="space-y-6">
					<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
						<div class="space-y-2.5">
							<Label class="text-sm font-medium">Nombre de Usuario</Label>
							<Input value={profile.username} disabled class="bg-muted/50" />
						</div>

						<div class="space-y-2.5">
							<Label class="text-sm font-medium">ID de Usuario</Label>
							<Input value={profile.id} disabled class="font-mono text-xs bg-muted/50" />
						</div>
					</div>
					<div class="space-y-2.5">
						<Label class="text-sm font-medium">Email</Label>
						<Input value={profile.email || ''} disabled class="bg-muted/50" />
						<p class="text-xs text-muted-foreground">
							Para cambiar tu email accede a tu perfil en el portal de Aduanasoft.
						</p>
					</div>
				</CardContent>
				</Card>
			</div>

			<!-- Messages -->
			{#if error}
				<div class="bg-destructive/15 text-destructive px-5 py-4 rounded-lg border border-destructive/20 shadow-sm">
					<p class="text-sm font-medium">{error}</p>
				</div>
			{/if}

			{#if success}
				<div class="bg-green-50 text-green-800 px-5 py-4 rounded-lg border border-green-200 shadow-sm">
					<p class="text-sm font-medium">{success}</p>
				</div>
			{/if}

			<!-- Actions - Sticky Footer -->
			<div class="fixed bottom-0 left-0 right-0 md:left-64 bg-background/95 backdrop-blur-sm border-t p-4 z-50">
				<div class="max-w-5xl mx-auto flex flex-col sm:flex-row justify-end gap-3">
					<Button 
						type="button" 
						variant="outline" 
						onclick={() => window.location.reload()} 
						disabled={saving}
						class="w-full sm:w-auto transition-all"
					>
						Cancelar
					</Button>
					<Button 
						type="submit" 
						disabled={saving}
						class="w-full sm:w-auto transition-all shadow-lg shadow-primary/20"
					>
						{saving ? 'Guardando...' : 'Guardar Cambios'}
					</Button>
				</div>
			</div>
		</form>
	{/if}
</div>
