<script lang="ts">
	import { enhance } from '$app/forms';
	import { goto } 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 { DatePicker, NationalitySelect, PhoneInput, CountrySelect } from '$lib/components/ui';
	import { FormMessage, LoadingSpinner } from '$lib/components/auth';
	import { CalendarDate, today, getLocalTimeZone } from '@internationalized/date';
	import { fly, fade } from 'svelte/transition';
	import { cubicOut, cubicIn } from 'svelte/easing';
	import {
		Sparkles,
		Users,
		Calendar,
		FileText,
		CreditCard,
		ArrowRight,
		ArrowLeft,
		Camera,
		Upload,
		Check,
		Mail,
		RefreshCw,
		ChevronRight
	} from 'lucide-svelte';

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

	// Wizard state - start at step 3 if already logged in (resuming onboarding)
	let currentStep = $state(data.session ? 3 : 1);
	let direction = $state<'forward' | 'backward'>('forward');
	let loading = $state(false);

	// Form data state
	let firstName = $state('');
	let lastName = $state('');
	let email = $state('');
	let phone = $state('');
	let phoneCountryCode = $state('US');
	let password = $state('');
	let confirmPassword = $state('');
	let selectedNationalities = $state<string[]>([]);
	let dateOfBirth = $state<CalendarDate | undefined>(undefined);
	let street = $state('');
	let city = $state('');
	let residenceCountry = $state('MC');
	let termsAccepted = $state(false);

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

	// Avatar state
	let avatarFile = $state<File | null>(null);
	let avatarPreview = $state<string | null>(null);
	let avatarUploading = $state(false);

	// Email verification state
	let emailVerified = $state(false);
	let verificationChecking = $state(false);
	let resendingEmail = $state(false);

	// Member data (set after account creation or from existing session)
	let memberId = $state<string | null>(data.member?.member_id || null);
	let memberEmail = $state<string | null>(data.member?.email || null);

	// Calculate max date for 18+ years old
	const todayDate = today(getLocalTimeZone());
	const maxDateOfBirth = new CalendarDate(
		todayDate.year - 18,
		todayDate.month,
		todayDate.day
	);

	// Step definitions
	const steps = [
		{ num: 1, title: 'Welcome', icon: Sparkles },
		{ num: 2, title: 'Your Info', icon: Users },
		{ num: 3, title: 'Photo', icon: Camera },
		{ num: 4, title: 'Tour', icon: Calendar },
		{ num: 5, title: 'Verify', icon: Mail },
		{ num: 6, title: 'Complete', icon: CreditCard }
	];

	// Benefits for welcome page
	const benefits = [
		{ icon: Calendar, title: 'Exclusive Events', description: 'Access member-only social gatherings, galas, and networking events' },
		{ icon: Users, title: 'Vibrant Community', description: 'Meet fellow Americans at Monaco USA events and build lasting connections' },
		{ icon: FileText, title: 'Member Resources', description: 'Documents, guides, and support for life in Monaco' },
		{ icon: Sparkles, title: 'Cultural Exchange', description: 'Bridge American and Monegasque communities' }
	];

	// Platform tour features
	const features = [
		{ icon: Sparkles, title: 'Dashboard', description: 'Your personalized hub with dues status, upcoming events, and community updates', color: 'bg-monaco-100 text-monaco-600' },
		{ icon: Calendar, title: 'Events', description: 'Browse and RSVP to exclusive member events, from galas to casual meetups', color: 'bg-blue-100 text-blue-600' },
		{ icon: Users, title: 'Community', description: 'Meet fellow Americans at our events and become part of our vibrant community', color: 'bg-green-100 text-green-600' },
		{ icon: FileText, title: 'Documents', description: 'Access important documents, meeting minutes, and member resources', color: 'bg-purple-100 text-purple-600' }
	];

	function nextStep() {
		direction = 'forward';
		currentStep = Math.min(currentStep + 1, 6);
	}

	function prevStep() {
		direction = 'backward';
		currentStep = Math.max(currentStep - 1, 1);
	}

	function handleAvatarSelect(event: Event) {
		const input = event.target as HTMLInputElement;
		const file = input.files?.[0];
		if (file) {
			avatarFile = file;
			const reader = new FileReader();
			reader.onload = (e) => {
				avatarPreview = e.target?.result as string;
			};
			reader.readAsDataURL(file);
		}
	}

	async function checkEmailVerification() {
		verificationChecking = true;
		try {
			const response = await fetch('/api/auth/check-verification');
			const result = await response.json();
			emailVerified = result.verified;
			if (emailVerified) {
				nextStep();
			}
		} catch (error) {
			console.error('Failed to check verification:', error);
		} finally {
			verificationChecking = false;
		}
	}

	async function resendVerificationEmail() {
		resendingEmail = true;
		try {
			await fetch('/api/auth/resend-verification', { method: 'POST' });
		} catch (error) {
			console.error('Failed to resend email:', error);
		} finally {
			resendingEmail = false;
		}
	}

	// Handle form results
	$effect(() => {
		if (form?.success && form?.step === 2) {
			// Account created successfully
			memberId = form.memberId;
			memberEmail = form.email;
			nextStep();
		}
		if (form?.success && form?.step === 3) {
			// Photo uploaded
			nextStep();
		}
		if (form?.success && form?.step === 6) {
			// Onboarding complete
			goto('/dashboard');
		}
	});
</script>

<svelte:head>
	<title>Join Monaco USA</title>
	<meta name="description" content="Join the Monaco USA community - Americans living in and connected to Monaco" />
</svelte:head>

<!-- Step Indicator -->
<div class="mb-2 sm:mb-3 md:mb-4">
	<div class="flex items-center justify-center gap-1 sm:gap-2">
		{#each steps as step}
			<div class="flex items-center">
				<div
					class="flex h-6 w-6 sm:h-8 sm:w-8 items-center justify-center rounded-full text-[10px] sm:text-xs font-semibold transition-all duration-300
					{currentStep === step.num
						? 'bg-white text-monaco-600 shadow-lg scale-110'
						: currentStep > step.num
							? 'bg-green-500 text-white'
							: 'bg-white/20 text-white/60'}"
				>
					{#if currentStep > step.num}
						<Check class="h-3 w-3 sm:h-4 sm:w-4" />
					{:else}
						{step.num}
					{/if}
				</div>
				{#if step.num < 6}
					<div
						class="mx-0.5 sm:mx-1 h-0.5 w-2 sm:w-4 hidden sm:block transition-all duration-300
						{currentStep > step.num ? 'bg-green-500' : 'bg-white/20'}"
					></div>
				{/if}
			</div>
		{/each}
	</div>
	<p class="mt-1.5 text-center text-xs sm:text-sm text-white/80">
		Step {currentStep} of 6: {steps[currentStep - 1].title}
	</p>
</div>

<!-- Wizard Card -->
<div class="overflow-hidden rounded-2xl bg-white shadow-xl">
	{#key currentStep}
		<div
			in:fly={{ x: direction === 'forward' ? 60 : -60, duration: 400, easing: cubicOut }}
			out:fly={{ x: direction === 'forward' ? -60 : 60, duration: 300, easing: cubicIn }}
		>
			<!-- Step 1: Welcome -->
			{#if currentStep === 1}
				<div class="p-4 sm:p-5 md:p-6">
					<div class="text-center">
						<h2 class="text-xl md:text-2xl font-bold text-slate-900">Welcome to Monaco USA</h2>
						<p class="mt-1 text-sm text-slate-600">Join our vibrant community of Americans in Monaco</p>
					</div>

					<div class="mt-4 sm:mt-5 grid gap-2 sm:gap-3 grid-cols-1 sm:grid-cols-2">
						{#each benefits as benefit, i}
							<div
								class="rounded-lg border border-slate-100 bg-slate-50 p-3 transition-all hover:border-monaco-200 hover:bg-monaco-50"
								in:fly={{ y: 20, delay: i * 100, duration: 300 }}
							>
								<div class="mb-1.5 flex h-8 w-8 items-center justify-center rounded-lg bg-monaco-100">
									<svelte:component this={benefit.icon} class="h-4 w-4 text-monaco-600" />
								</div>
								<h3 class="text-sm font-semibold text-slate-900">{benefit.title}</h3>
								<p class="mt-0.5 text-xs text-slate-600">{benefit.description}</p>
							</div>
						{/each}
					</div>

					<div class="mt-4 sm:mt-5">
						<Button variant="monaco" size="default" class="w-full" onclick={nextStep}>
							Get Started
							<ArrowRight class="ml-2 h-4 w-4" />
						</Button>
					</div>

					<p class="mt-3 text-center text-sm text-slate-500">
						Already have an account?
						<a href="/login" class="font-medium text-monaco-600 hover:underline">Sign in</a>
					</p>
				</div>
			{/if}

			<!-- Step 2: Your Information -->
			{#if currentStep === 2}
				<div class="p-4 sm:p-5 md:p-6">
					<div class="text-center">
						<div class="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-monaco-100">
							<Users class="h-6 w-6 text-monaco-600" />
						</div>
						<h2 class="mt-3 text-lg font-bold text-slate-900">Your Information</h2>
						<p class="mt-1 text-sm text-slate-600">Tell us about yourself to create your account</p>
					</div>

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

					<form
						method="POST"
						action="?/createAccount"
						use:enhance={() => {
							loading = true;
							return async ({ update }) => {
								loading = false;
								await update();
							};
						}}
						class="mt-4 space-y-3"
					>
						<!-- Name Row -->
						<div class="grid grid-cols-1 sm:grid-cols-2 gap-2 sm:gap-3">
							<div class="space-y-1">
								<Label for="first_name" class="text-sm font-medium text-slate-700">
									First name <span class="text-monaco-600">*</span>
								</Label>
								<Input
									id="first_name"
									name="first_name"
									type="text"
									placeholder="John"
									required
									disabled={loading}
									bind:value={firstName}
									class="h-10"
									autocomplete="given-name"
								/>
							</div>
							<div class="space-y-1">
								<Label for="last_name" class="text-sm font-medium text-slate-700">
									Last name <span class="text-monaco-600">*</span>
								</Label>
								<Input
									id="last_name"
									name="last_name"
									type="text"
									placeholder="Doe"
									required
									disabled={loading}
									bind:value={lastName}
									class="h-10"
									autocomplete="family-name"
								/>
							</div>
						</div>

						<!-- Email -->
						<div class="space-y-1">
							<Label for="email" class="text-sm font-medium text-slate-700">
								Email <span class="text-monaco-600">*</span>
							</Label>
							<Input
								id="email"
								name="email"
								type="email"
								placeholder="you@example.com"
								required
								disabled={loading}
								bind:value={email}
								class="h-10"
								autocomplete="email"
							/>
						</div>

						<!-- Phone -->
						<div class="space-y-1">
							<Label class="text-sm font-medium text-slate-700">
								Phone <span class="text-monaco-600">*</span>
							</Label>
							<PhoneInput
								bind:value={phone}
								bind:countryCode={phoneCountryCode}
								disabled={loading}
								placeholder="Phone number"
								name="phone"
								required
							/>
						</div>

						<!-- Nationality -->
						<div class="space-y-1">
							<Label class="text-sm font-medium text-slate-700">
								Nationality <span class="text-monaco-600">*</span>
							</Label>
							<NationalitySelect
								bind:value={selectedNationalities}
								disabled={loading}
								placeholder="Search and select nationalities..."
								name="nationality"
							/>
						</div>

						<!-- Date of Birth -->
						<div class="space-y-1">
							<Label class="text-sm font-medium text-slate-700">
								Date of birth <span class="text-monaco-600">*</span>
							</Label>
							<DatePicker
								bind:value={dateOfBirth}
								maxValue={maxDateOfBirth}
								disabled={loading}
								placeholder="Select your birth date"
								name="date_of_birth"
							/>
							<p class="text-xs text-slate-500">You must be at least 18 years old.</p>
						</div>

						<!-- Street Address -->
						<div class="space-y-1">
							<Label for="street" class="text-sm font-medium text-slate-700">
								Street address <span class="text-monaco-600">*</span>
							</Label>
							<Input
								id="street"
								name="street"
								type="text"
								placeholder="123 Avenue Princesse Grace"
								required
								disabled={loading}
								bind:value={street}
								class="h-10"
								autocomplete="street-address"
							/>
						</div>

						<!-- City & Country of Residence -->
						<div class="grid grid-cols-1 sm:grid-cols-2 gap-2 sm:gap-3">
							<div class="space-y-1">
								<Label for="city" class="text-sm font-medium text-slate-700">
									City <span class="text-monaco-600">*</span>
								</Label>
								<Input
									id="city"
									name="city"
									type="text"
									placeholder="Monaco"
									required
									disabled={loading}
									bind:value={city}
									class="h-10"
									autocomplete="address-level2"
								/>
							</div>
							<div class="space-y-1">
								<Label class="text-sm font-medium text-slate-700">
									Country of residence <span class="text-monaco-600">*</span>
								</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} />

						<!-- Password -->
						<div class="grid grid-cols-1 sm:grid-cols-2 gap-2 sm:gap-3">
							<div class="space-y-1">
								<Label for="password" class="text-sm font-medium text-slate-700">
									Password <span class="text-monaco-600">*</span>
								</Label>
								<Input
									id="password"
									name="password"
									type="password"
									placeholder="Min 8 characters"
									required
									disabled={loading}
									bind:value={password}
									minlength={8}
									class="h-10"
									autocomplete="new-password"
								/>
							</div>
							<div class="space-y-1">
								<Label for="confirm_password" class="text-sm font-medium text-slate-700">
									Confirm <span class="text-monaco-600">*</span>
								</Label>
								<Input
									id="confirm_password"
									name="confirm_password"
									type="password"
									placeholder="Confirm password"
									required
									disabled={loading}
									bind:value={confirmPassword}
									minlength={8}
									class="h-10"
									autocomplete="new-password"
								/>
							</div>
						</div>

						<!-- Terms -->
						<div class="flex items-start gap-2 sm:gap-3">
							<input
								type="checkbox"
								id="terms"
								name="terms"
								required
								bind:checked={termsAccepted}
								class="mt-1 h-5 w-5 rounded border-slate-300 text-monaco-600 focus:ring-monaco-500 transition-colors"
							/>
							<label for="terms" class="text-sm text-slate-600">
								I agree to the
								<a href="/terms" target="_blank" class="text-monaco-600 hover:underline">Terms of Service</a>
								and
								<a href="/privacy" target="_blank" class="text-monaco-600 hover:underline">Privacy Policy</a>.
							</label>
						</div>

						<div class="flex gap-3 pt-2">
							<Button type="button" variant="outline" size="lg" class="flex-1" onclick={prevStep} disabled={loading}>
								<ArrowLeft class="mr-2 h-4 w-4" />
								Back
							</Button>
							<Button type="submit" variant="monaco" size="lg" class="flex-1" disabled={loading}>
								{#if loading}
									<LoadingSpinner size="sm" class="mr-2" />
									Creating...
								{:else}
									Continue
									<ArrowRight class="ml-2 h-4 w-4" />
								{/if}
							</Button>
						</div>
					</form>
				</div>
			{/if}

			<!-- Step 3: Profile Photo -->
			{#if currentStep === 3}
				<div class="p-4 sm:p-5 md:p-6">
					<div class="text-center">
						<h2 class="text-lg font-bold text-slate-900">Add a Profile Photo</h2>
						<p class="text-sm text-slate-600">Help other members recognize you (optional)</p>
					</div>

					<div class="mt-5 flex flex-col items-center">
						<div class="relative">
							{#if avatarPreview}
								<img
									src={avatarPreview}
									alt="Profile preview"
									class="h-32 w-32 rounded-full object-cover shadow-lg"
								/>
							{:else}
								<div class="flex h-32 w-32 items-center justify-center rounded-full bg-slate-100">
									<Camera class="h-12 w-12 text-slate-400" />
								</div>
							{/if}
							<label
								class="absolute bottom-0 right-0 flex h-10 w-10 cursor-pointer items-center justify-center rounded-full bg-monaco-600 text-white shadow-lg transition-colors hover:bg-monaco-700"
							>
								<Upload class="h-5 w-5" />
								<input
									type="file"
									accept="image/jpeg,image/png,image/webp"
									class="hidden"
									onchange={handleAvatarSelect}
								/>
							</label>
						</div>

						<p class="mt-4 text-sm text-slate-500">
							JPEG, PNG, or WebP. Max 5MB.
						</p>

						<form
							method="POST"
							action="?/uploadPhoto"
							enctype="multipart/form-data"
							use:enhance={() => {
								avatarUploading = true;
								return async ({ update }) => {
									avatarUploading = false;
									await update();
								};
							}}
							class="mt-6 w-full"
						>
							{#if avatarFile}
								<input type="hidden" name="hasAvatar" value="true" />
							{/if}

							<div class="flex gap-3">
								<Button type="button" variant="outline" size="lg" class="flex-1" onclick={prevStep}>
									<ArrowLeft class="mr-2 h-4 w-4" />
									Back
								</Button>
								<Button
									type="button"
									variant="ghost"
									size="lg"
									class="flex-1"
									onclick={nextStep}
								>
									Skip
									<ChevronRight class="ml-2 h-4 w-4" />
								</Button>
								{#if avatarFile}
									<Button type="submit" variant="monaco" size="lg" class="flex-1" disabled={avatarUploading}>
										{#if avatarUploading}
											<LoadingSpinner size="sm" class="mr-2" />
											Uploading...
										{:else}
											Continue
											<ArrowRight class="ml-2 h-4 w-4" />
										{/if}
									</Button>
								{/if}
							</div>
						</form>
					</div>
				</div>
			{/if}

			<!-- Step 4: Platform Tour -->
			{#if currentStep === 4}
				<div class="p-4 sm:p-5 md:p-6">
					<div class="text-center">
						<h2 class="text-lg font-bold text-slate-900">Explore Your New Home</h2>
						<p class="text-sm text-slate-600">Here's what you'll have access to as a member</p>
					</div>

					<div class="mt-4 space-y-2">
						{#each features as feature, i}
							<div
								class="flex items-start gap-3 rounded-lg border border-slate-100 p-3 transition-all hover:border-slate-200 hover:bg-slate-50"
								in:fly={{ x: 50, delay: i * 100, duration: 300 }}
							>
								<div class="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-lg {feature.color}">
									<svelte:component this={feature.icon} class="h-5 w-5" />
								</div>
								<div>
									<h3 class="text-sm font-semibold text-slate-900">{feature.title}</h3>
									<p class="text-xs text-slate-600">{feature.description}</p>
								</div>
							</div>
						{/each}
					</div>

					<div class="mt-4 flex gap-3">
						<Button type="button" variant="outline" size="default" class="flex-1" onclick={prevStep}>
							<ArrowLeft class="mr-2 h-4 w-4" />
							Back
						</Button>
						<Button type="button" variant="monaco" size="default" class="flex-1" onclick={nextStep}>
							Continue
							<ArrowRight class="ml-2 h-4 w-4" />
						</Button>
					</div>
				</div>
			{/if}

			<!-- Step 5: Verify Email -->
			{#if currentStep === 5}
				<div class="p-4 sm:p-5 md:p-6">
					<div class="text-center">
						<div class="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-monaco-100">
							<Mail class="h-6 w-6 text-monaco-600" />
						</div>
						<h2 class="mt-3 text-lg font-bold text-slate-900">Verify Your Email</h2>
						<p class="mt-1 text-sm text-slate-600">
							We sent a verification link to<br />
							<strong class="text-slate-900">{memberEmail || email}</strong>
						</p>
					</div>

					<div class="mt-4 rounded-lg bg-slate-50 p-4 text-center">
						<p class="text-sm text-slate-600">
							Click the link in your email to verify your address, then click the button below.
						</p>
					</div>

					<div class="mt-4 space-y-2">
						<Button
							type="button"
							variant="monaco"
							size="default"
							class="w-full"
							onclick={checkEmailVerification}
							disabled={verificationChecking}
						>
							{#if verificationChecking}
								<LoadingSpinner size="sm" class="mr-2" />
								Checking...
							{:else}
								I've Verified My Email
								<ArrowRight class="ml-2 h-4 w-4" />
							{/if}
						</Button>

						<Button
							type="button"
							variant="ghost"
							size="default"
							class="w-full"
							onclick={resendVerificationEmail}
							disabled={resendingEmail}
						>
							{#if resendingEmail}
								<LoadingSpinner size="sm" class="mr-2" />
								Sending...
							{:else}
								<RefreshCw class="mr-2 h-4 w-4" />
								Resend Verification Email
							{/if}
						</Button>
					</div>

					<div class="mt-4">
						<Button type="button" variant="outline" size="default" class="w-full" onclick={prevStep}>
							<ArrowLeft class="mr-2 h-4 w-4" />
							Back
						</Button>
					</div>
				</div>
			{/if}

			<!-- Step 6: Payment & Complete -->
			{#if currentStep === 6}
				<div class="p-4 sm:p-5 md:p-6">
					<div class="text-center">
						<div class="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-green-100">
							<Check class="h-6 w-6 text-green-600" />
						</div>
						<h2 class="mt-2 text-lg font-bold text-slate-900">You're Almost There!</h2>
						<p class="mt-1 text-sm text-slate-600">
							Complete your membership by paying your annual dues within 30 days
						</p>
					</div>

					<div class="mt-4 rounded-lg bg-slate-50 p-4">
						<div class="text-center">
							<p class="text-xs text-slate-500">Annual Membership</p>
							<p class="text-2xl font-bold text-monaco-600">€{data?.duesAmount || '150'}</p>
						</div>
					</div>

					<div class="mt-3 rounded-lg bg-blue-50 border border-blue-200 p-4">
						<h3 class="text-sm font-semibold text-blue-900">Bank Transfer Details</h3>
						<div class="mt-2 space-y-1.5 text-sm">
							<p class="flex justify-between">
								<span class="text-blue-700">Account Holder:</span>
								<span class="font-medium text-blue-900">{data?.paymentSettings?.account_holder || 'Monaco USA'}</span>
							</p>
							<p class="flex justify-between">
								<span class="text-blue-700">Bank:</span>
								<span class="font-medium text-blue-900">{data?.paymentSettings?.bank_name || 'Credit Foncier de Monaco'}</span>
							</p>
							<p class="flex justify-between">
								<span class="text-blue-700">IBAN:</span>
								<span class="font-mono font-medium text-blue-900">{data?.paymentSettings?.iban || 'MC58...'}</span>
							</p>
							<p class="flex justify-between">
								<span class="text-blue-700">Reference:</span>
								<span class="font-mono font-medium text-blue-900">{memberId || 'MUSA-2026-XXXX'}</span>
							</p>
						</div>
					</div>

					<div class="mt-3 rounded-lg bg-amber-50 border border-amber-200 p-3">
						<h4 class="text-sm font-medium text-amber-900">What Happens Next?</h4>
						<ul class="mt-1.5 space-y-0.5 text-xs text-amber-800">
							<li>• Check your email for confirmation</li>
							<li>• Make your bank transfer within 30 days</li>
							<li>• We'll activate your account once payment is received</li>
						</ul>
					</div>

					<form
						method="POST"
						action="?/complete"
						use:enhance={() => {
							loading = true;
							return async ({ update }) => {
								loading = false;
								await update();
							};
						}}
						class="mt-4"
					>
						<Button type="submit" variant="monaco" size="default" class="w-full" disabled={loading}>
							{#if loading}
								<LoadingSpinner size="sm" class="mr-2" />
								Completing...
							{:else}
								Go to Dashboard
								<ArrowRight class="ml-2 h-4 w-4" />
							{/if}
						</Button>
					</form>
				</div>
			{/if}
		</div>
	{/key}
</div>
