<script lang="ts">
	import { enhance } from '$app/forms';
	import { invalidateAll } from '$app/navigation';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { NationalitySelect, PhoneInput, CountrySelect } from '$lib/components/ui';
	import { FormMessage, LoadingSpinner } from '$lib/components/auth';
	import { Camera, Save, Trash2, Upload } from 'lucide-svelte';

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

	// Use $derived for reactivity after invalidateAll()
	const member = $derived(data.member);

	let loading = $state(false);
	let avatarLoading = $state(false);
	let selectedNationalities = $state<string[]>(data.member?.nationality || []);

	// Phone state
	let phoneValue = $state(data.member?.phone || '');
	let phoneCountryCode = $state('US');

	// Address state
	let street = $state('');
	let city = $state('');
	let residenceCountry = $state('MC');

	// Parse address when member data loads
	$effect(() => {
		if (member?.phone && !phoneValue) {
			phoneValue = member.phone;
		}
		if (member?.address) {
			// Try to parse existing address (format: "street, city, country")
			const parts = member.address.split(',').map((p: string) => p.trim());
			if (parts.length >= 3) {
				street = parts.slice(0, -2).join(', ');
				city = parts[parts.length - 2] || '';
				residenceCountry = parts[parts.length - 1] || 'MC';
			} else if (parts.length === 2) {
				street = parts[0] || '';
				city = parts[1] || '';
			} else {
				street = member.address;
			}
		}
	});

	// Computed full address for database
	const fullAddress = $derived(`${street}, ${city}, ${residenceCountry}`);

	function triggerAvatarUpload() {
		const input = document.getElementById('avatar-file-input') as HTMLInputElement;
		input?.click();
	}
</script>

<svelte:head>
	<title>My Profile | Monaco USA</title>
</svelte:head>

<div class="mx-auto max-w-3xl space-y-6">
	<!-- Profile Header -->
	<div class="glass-card p-6">
		<div class="flex flex-col items-center gap-4 sm:flex-row sm:items-start">
			<!-- Avatar -->
			<div class="relative">
				{#if member?.avatar_url}
					<img
						src={member.avatar_url}
						alt={`${member.first_name} ${member.last_name}`}
						class="h-24 w-24 rounded-full object-cover ring-4 ring-white shadow-lg"
					/>
				{:else}
					<div
						class="flex h-24 w-24 items-center justify-center rounded-full bg-monaco-100 text-2xl font-semibold text-monaco-700 ring-4 ring-white shadow-lg"
					>
						{member?.first_name[0]}{member?.last_name[0]}
					</div>
				{/if}

				<!-- Avatar Upload Form -->
				<form
					method="POST"
					action="?/uploadAvatar"
					enctype="multipart/form-data"
					use:enhance={() => {
						avatarLoading = true;
						return async ({ update }) => {
							await invalidateAll();
							avatarLoading = false;
							await update();
						};
					}}
					class="absolute bottom-0 right-0"
				>
					<input
						type="file"
						id="avatar-file-input"
						name="avatar"
						accept="image/jpeg,image/png,image/webp,image/gif"
						onchange={(e) => e.currentTarget.form?.requestSubmit()}
						class="hidden"
					/>
					<button
						type="button"
						onclick={triggerAvatarUpload}
						disabled={avatarLoading}
						class="flex h-8 w-8 items-center justify-center rounded-full bg-monaco-600 text-white shadow-md hover:bg-monaco-700 disabled:opacity-50"
						aria-label="Change photo"
					>
						{#if avatarLoading}
							<LoadingSpinner size="sm" />
						{:else}
							<Camera class="h-4 w-4" />
						{/if}
					</button>
				</form>

				<!-- Remove Avatar Button -->
				{#if member?.avatar_url}
					<form
						method="POST"
						action="?/removeAvatar"
						use:enhance={() => {
							avatarLoading = true;
							return async ({ update }) => {
								await invalidateAll();
								avatarLoading = false;
								await update();
							};
						}}
						class="absolute -bottom-2 -right-2"
					>
						<button
							type="submit"
							disabled={avatarLoading}
							class="flex h-6 w-6 items-center justify-center rounded-full bg-red-500 text-white shadow-md hover:bg-red-600 disabled:opacity-50"
							aria-label="Remove photo"
							title="Remove photo"
						>
							<Trash2 class="h-3 w-3" />
						</button>
					</form>
				{/if}
			</div>

			<div class="flex-1 text-center sm:text-left">
				<h2 class="text-xl font-semibold text-slate-900">
					{member?.first_name}
					{member?.last_name}
				</h2>
				<p class="text-slate-500">{member?.email}</p>
				<div class="mt-2 flex flex-wrap items-center justify-center gap-2 sm:justify-start">
					<span
						class="inline-flex items-center rounded-full bg-monaco-100 px-2.5 py-0.5 text-xs font-medium text-monaco-700"
					>
						{member?.member_id}
					</span>
					<span
						class="inline-flex items-center rounded-full bg-green-100 px-2.5 py-0.5 text-xs font-medium text-green-700"
					>
						{member?.status_display_name || 'Pending'}
					</span>
					{#if member?.role !== 'member'}
						<span
							class="inline-flex items-center rounded-full bg-purple-100 px-2.5 py-0.5 text-xs font-medium capitalize text-purple-700"
						>
							{member?.role}
						</span>
					{/if}
				</div>
			</div>
		</div>
	</div>

	<!-- Edit Form -->
	<div class="glass-card p-6">
		<h3 class="mb-6 text-lg font-semibold text-slate-900">Personal Information</h3>

		{#if form?.error}
			<div class="mb-4">
				<FormMessage type="error" message={form.error} />
			</div>
		{/if}

		{#if form?.success}
			<div class="mb-4">
				<FormMessage type="success" message={form.success} />
			</div>
		{/if}

		<form
			method="POST"
			action="?/updateProfile"
			use:enhance={() => {
				loading = true;
				return async ({ update }) => {
					await invalidateAll();
					loading = false;
					await update();
				};
			}}
			class="space-y-6"
		>
			<!-- Name Row -->
			<div class="grid gap-4 sm:grid-cols-2">
				<div class="space-y-2">
					<Label for="first_name">First name</Label>
					<Input
						id="first_name"
						name="first_name"
						type="text"
						value={member?.first_name}
						required
						disabled={loading}
						class="h-11"
					/>
				</div>
				<div class="space-y-2">
					<Label for="last_name">Last name</Label>
					<Input
						id="last_name"
						name="last_name"
						type="text"
						value={member?.last_name}
						required
						disabled={loading}
						class="h-11"
					/>
				</div>
			</div>

			<!-- Email (read-only) -->
			<div class="space-y-2">
				<Label for="email">Email address</Label>
				<Input
					id="email"
					type="email"
					value={member?.email}
					disabled
					class="h-11 bg-slate-50"
				/>
				<p class="text-xs text-slate-500">
					<a href="/settings?tab=security" class="text-monaco-600 hover:text-monaco-700 hover:underline">
						Change email in Account Settings →
					</a>
				</p>
			</div>

			<!-- Phone -->
			<div class="space-y-2">
				<Label>Phone number</Label>
				<PhoneInput
					bind:value={phoneValue}
					bind:countryCode={phoneCountryCode}
					disabled={loading}
					placeholder="Phone number"
					name="phone"
					required
				/>
			</div>

			<!-- Street Address -->
			<div class="space-y-2">
				<Label for="street">Street address</Label>
				<Input
					id="street"
					name="street"
					type="text"
					bind:value={street}
					placeholder="123 Avenue Princesse Grace"
					required
					disabled={loading}
					class="h-11"
				/>
			</div>

			<!-- City & Country -->
			<div class="grid gap-4 sm:grid-cols-2">
				<div class="space-y-2">
					<Label for="city">City</Label>
					<Input
						id="city"
						name="city"
						type="text"
						bind:value={city}
						placeholder="Monaco"
						required
						disabled={loading}
						class="h-11"
					/>
				</div>
				<div class="space-y-2">
					<Label>Country of residence</Label>
					<CountrySelect
						bind:value={residenceCountry}
						disabled={loading}
						placeholder="Select country..."
						name="residence_country"
						required
					/>
				</div>
			</div>

			<!-- Hidden full address for database -->
			<input type="hidden" name="address" value={fullAddress} />

			<!-- Nationality - New Dropdown Select -->
			<div class="space-y-2">
				<Label>Nationality</Label>
				<NationalitySelect
					bind:value={selectedNationalities}
					disabled={loading}
					placeholder="Search and select nationalities..."
					name="nationality"
				/>
			</div>

			<div class="flex justify-end">
				<Button type="submit" variant="monaco" disabled={loading}>
					{#if loading}
						<LoadingSpinner size="sm" class="mr-2" />
						Saving...
					{:else}
						<Save class="mr-2 h-4 w-4" />
						Save changes
					{/if}
				</Button>
			</div>
		</form>
	</div>

	<!-- Membership Info (read-only) -->
	<div class="glass-card p-6">
		<h3 class="mb-4 text-lg font-semibold text-slate-900">Membership Details</h3>

		<dl class="grid gap-4 sm:grid-cols-2">
			<div>
				<dt class="text-sm text-slate-500">Member ID</dt>
				<dd class="font-medium text-slate-900">{member?.member_id}</dd>
			</div>
			<div>
				<dt class="text-sm text-slate-500">Membership Type</dt>
				<dd class="font-medium text-slate-900">{member?.membership_type_name || 'Regular'}</dd>
			</div>
			<div>
				<dt class="text-sm text-slate-500">Member Since</dt>
				<dd class="font-medium text-slate-900">
					{member?.member_since
						? new Date(member.member_since).toLocaleDateString('en-US', {
								year: 'numeric',
								month: 'long',
								day: 'numeric'
							})
						: 'N/A'}
				</dd>
			</div>
			<div>
				<dt class="text-sm text-slate-500">Date of Birth</dt>
				<dd class="font-medium text-slate-900">
					{member?.date_of_birth
						? new Date(member.date_of_birth).toLocaleDateString('en-US', {
								year: 'numeric',
								month: 'long',
								day: 'numeric'
							})
						: 'N/A'}
				</dd>
			</div>
		</dl>
	</div>
</div>
