<script lang="ts">
	import { enhance } from '$app/forms';
	import type { PageData } from './$types';
	import { resolve } from '$app/paths';
	import { t, language } from '$lib/i18n';

	interface Props {
		data: PageData;
		form?: { success?: boolean; message?: string } | null;
	}

	interface DailyHistoryEntry {
		id: string;
		characterId: string | null;
		date: number;
		tryCount: number;
		won: number;
		characterName: string;
		characterImage: string | null;
		triedCharacters?: Array<{
			id: string;
			name: string;
			pictureUrl: string | null;
		}>;
	}

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

	let isLoading = $state(false);
	let activeTab = $state<'profile' | 'password' | 'sessions' | 'daily' | 'friends'>('profile');
	let name = $derived(data.user?.name || '');
	let friendUsername = $state('');
	let showSuccess = $state(false);
	let oldPassword = $state('');
	let newPassword = $state('');
	let confirmPassword = $state('');
	let sessions = $derived(data.sessions || []);
	let dailyHistory = $derived((data.dailyHistory || []) as DailyHistoryEntry[]);
	let friends = $derived(data.friends || []);
	let incomingRequests = $derived(data.incomingRequests || []);
	let outgoingRequests = $derived(data.outgoingRequests || []);
	let tabsElement: HTMLDivElement | undefined;

	$effect(() => {
		friends = data.friends || [];
	});

	$effect(() => {
		incomingRequests = data.incomingRequests || [];
	});

	$effect(() => {
		outgoingRequests = data.outgoingRequests || [];
	});

	$effect(() => {
		if (form && form.success === true) {
			showSuccess = true;
			setTimeout(() => {
				showSuccess = false;
			}, 3000);
		}
	});

	const handleTabChange = (tab: 'profile' | 'password' | 'sessions' | 'daily' | 'friends') => {
		activeTab = tab;
	};

	const handleSubmit = () => {
		// Just for type purposes
	};
</script>

<svelte:head>
	<title>{$t.game.profile.pageTitle} - OnePieceDle</title>
</svelte:head>

<main class="relative min-h-[calc(100vh-5rem)] bg-slate-950 text-slate-100">
	<div class="absolute inset-0 bg-linear-to-br from-slate-950/85 via-slate-900/60 to-slate-950/80"></div>
	<div class="absolute inset-0 mix-blend-screen opacity-20 bg-[radial-gradient(circle_at_top,rgba(255,215,84,0.35),transparent_55%)]"></div>

	<div class="relative mx-auto flex w-full max-w-2xl flex-col items-center px-6 py-4">
		<div class="w-full space-y-4">
			<!-- Header -->
			<div class="text-center">
				<h1 class="text-3xl font-black uppercase tracking-[0.3em] text-amber-50 sm:text-4xl">
					{$t.game.profile.headerTitle}
				</h1>
				<p class="mt-2 text-sm text-slate-300">
					{$t.game.profile.headerSubtitle}
				</p>
			</div>

			<!-- Tabs Navigation -->
			<div bind:this={tabsElement} class="sticky top-20 z-10 flex gap-2 border-b border-white/10 bg-slate-950/80 backdrop-blur">
				<button
					onclick={() => handleTabChange('profile')}
					class="px-4 py-3 font-semibold uppercase tracking-widest transition {activeTab === 'profile'
						? 'border-b-2 border-amber-300 text-amber-100'
						: 'text-slate-400 hover:text-slate-100'}"
				>
					{$t.game.profile.tabProfile}
				</button>
				<button
					onclick={() => handleTabChange('password')}
					class="px-4 py-3 font-semibold uppercase tracking-widest transition {activeTab === 'password'
						? 'border-b-2 border-amber-300 text-amber-100'
						: 'text-slate-400 hover:text-slate-100'}"
				>
					{$t.game.profile.tabPassword}
				</button>
				<button
					onclick={() => handleTabChange('daily')}
					class="px-4 py-3 font-semibold uppercase tracking-widest transition {activeTab === 'daily'
						? 'border-b-2 border-amber-300 text-amber-100'
						: 'text-slate-400 hover:text-slate-100'}"
				>
					{$t.game.profile.tabDaily}
				</button>
				<button
					onclick={() => handleTabChange('sessions')}
					class="px-4 py-3 font-semibold uppercase tracking-widest transition {activeTab === 'sessions'
						? 'border-b-2 border-amber-300 text-amber-100'
						: 'text-slate-400 hover:text-slate-100'}"
				>
					{$t.game.profile.tabSessions}
				</button>
				<button
					onclick={() => handleTabChange('friends')}
					class="px-4 py-3 font-semibold uppercase tracking-widest transition {activeTab === 'friends'
						? 'border-b-2 border-amber-300 text-amber-100'
						: 'text-slate-400 hover:text-slate-100'}"
				>
					{$t.game.profile.tabFriends}
				</button>
			</div>

			<!-- Tab Content -->
			{#if activeTab === 'profile'}
			<div class="rounded-3xl border border-white/10 bg-white/5 p-6 shadow-[0_24px_60px_rgba(0,0,0,0.45)] backdrop-blur sm:p-8">
				<!-- Avatar -->
				<div class="mb-6 flex flex-col items-center gap-4">
					{#if data.user.image}
						<img
							src={data.user.image}
							alt={data.user.name || $t.game.profile.avatarFallbackAlt}
							class="h-24 w-24 rounded-full border-2 border-amber-300 object-cover"
						/>
					{:else}
						<div class="flex h-24 w-24 items-center justify-center rounded-full border-2 border-amber-300 bg-amber-300/20 text-2xl font-semibold text-amber-100">
							{data.user.name?.charAt(0).toUpperCase() || 'U'}
						</div>
					{/if}
					<div class="text-center">
						<p class="text-sm text-slate-400">{$t.game.profile.email}</p>
						<p class="font-semibold text-white">{data.user.email}</p>
					</div>
				</div>

				<!-- Form -->
				<form
					method="POST"
					action="?/updateProfile"
					use:enhance={() => {
						isLoading = true;
						return async ({ update }) => {
							isLoading = false;
							await update();
						};
					}}
					onsubmit={handleSubmit}
					class="space-y-6"
				>
					<!-- Name Field -->
					<div>
						<label for="name" class="block text-sm font-semibold uppercase tracking-[0.2em] text-amber-100">
							{$t.game.profile.displayName}
						</label>
						<input
							id="name"
							type="text"
							name="name"
							bind:value={name}
							required
							placeholder={$t.game.profile.displayNamePlaceholder}
							class="mt-3 w-full rounded-lg border border-white/10 bg-white/5 px-4 py-3 text-white placeholder-slate-500 transition focus:border-amber-300 focus:outline-none focus:ring-2 focus:ring-amber-300/30"
						/>
					</div>

					<!-- Error Message -->
					{#if form && form.message && form.success !== true}
						<div class="rounded-lg border border-red-500/30 bg-red-900/20 px-4 py-3 text-sm text-red-200">
							{form.message}
						</div>
					{/if}

					<!-- Success Message -->
					{#if showSuccess}
						<div class="rounded-lg border border-green-500/30 bg-green-900/20 px-4 py-3 text-sm text-green-200">
							{$t.game.profile.profileUpdateSuccess}
						</div>
					{/if}

					<!-- Submit Button -->
					<button
						type="submit"
						disabled={isLoading}
						class="w-full rounded-full bg-amber-300 px-6 py-3 text-sm font-semibold text-slate-900 transition disabled:opacity-50 hover:bg-amber-200"
					>
						{isLoading ? $t.game.profile.updating : $t.game.profile.saveChanges}
					</button>
				</form>
			</div>
			{/if}

			<!-- Friends Tab -->
			{#if activeTab === 'friends'}
			<div class="rounded-3xl border border-white/10 bg-white/5 p-6 shadow-[0_24px_60px_rgba(0,0,0,0.45)] backdrop-blur sm:p-8">
				<h2 class="mb-6 text-2xl font-bold uppercase tracking-[0.2em] text-amber-50">
					{$t.game.profile.friendsTitle}
				</h2>

				<form
					method="POST"
					action="?/sendFriendRequest"
					use:enhance={() => {
						isLoading = true;
						return async ({ update }) => {
							isLoading = false;
							friendUsername = '';
							await update();
						};
					}}
					class="mb-8 space-y-3"
				>
					<label for="friendUsername" class="block text-sm font-semibold uppercase tracking-[0.2em] text-amber-100">
						{$t.game.profile.addFriendByUsername}
					</label>
					<div class="flex gap-2">
						<input
							id="friendUsername"
							type="text"
							name="friendUsername"
							required
							bind:value={friendUsername}
							placeholder={$t.game.profile.friendUsernamePlaceholder}
							class="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-3 text-white placeholder-slate-500 transition focus:border-amber-300 focus:outline-none focus:ring-2 focus:ring-amber-300/30"
						/>
						<button
							type="submit"
							disabled={isLoading}
							class="rounded-full bg-amber-300 px-4 py-2 text-sm font-semibold text-slate-900 transition disabled:opacity-50 hover:bg-amber-200"
						>
							{isLoading ? $t.game.profile.sending : $t.game.profile.send}
						</button>
					</div>
					{#if form?.message}
						<p class="text-sm {form.success ? 'text-green-300' : 'text-red-300'}">{form.message}</p>
					{/if}
				</form>

				<div class="space-y-8">
					<div>
						<h3 class="mb-3 text-sm font-semibold uppercase tracking-[0.15em] text-amber-100">{$t.game.profile.incomingRequests}</h3>
						{#if incomingRequests.length === 0}
							<p class="text-sm text-slate-400">{$t.game.profile.noIncomingRequests}</p>
						{:else}
							<div class="space-y-3">
								{#each incomingRequests as req (req.id)}
									<div class="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-white/10 bg-white/5 px-4 py-3">
										<div>
											<p class="font-semibold text-white">{req.requesterName}</p>
												<p class="text-xs text-slate-400">@{req.requesterUsername}</p>
										</div>
										<div class="flex gap-2">
											<form method="POST" action="?/acceptFriendRequest" use:enhance>
												<input type="hidden" name="friendshipId" value={req.id} />
												<button type="submit" class="rounded-lg border border-emerald-400/50 bg-emerald-900/20 px-3 py-1.5 text-xs font-semibold text-emerald-300 transition hover:bg-emerald-900/40">{$t.game.profile.accept}</button>
											</form>
											<form method="POST" action="?/declineFriendRequest" use:enhance>
												<input type="hidden" name="friendshipId" value={req.id} />
												<button type="submit" class="rounded-lg border border-red-500/50 bg-red-900/20 px-3 py-1.5 text-xs font-semibold text-red-300 transition hover:bg-red-900/40">{$t.game.profile.decline}</button>
											</form>
										</div>
									</div>
								{/each}
							</div>
						{/if}
					</div>

					<div>
						<h3 class="mb-3 text-sm font-semibold uppercase tracking-[0.15em] text-amber-100">{$t.game.profile.outgoingRequests}</h3>
						{#if outgoingRequests.length === 0}
							<p class="text-sm text-slate-400">{$t.game.profile.noOutgoingRequests}</p>
						{:else}
							<div class="space-y-3">
								{#each outgoingRequests as req (req.id)}
									<div class="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-white/10 bg-white/5 px-4 py-3">
										<div>
											<p class="font-semibold text-white">{req.addresseeName}</p>
												<p class="text-xs text-slate-400">@{req.addresseeUsername}</p>
										</div>
										<form method="POST" action="?/cancelFriendRequest" use:enhance>
											<input type="hidden" name="friendshipId" value={req.id} />
											<button type="submit" class="rounded-lg border border-red-500/50 bg-red-900/20 px-3 py-1.5 text-xs font-semibold text-red-300 transition hover:bg-red-900/40">{$t.game.profile.cancel}</button>
										</form>
									</div>
								{/each}
							</div>
						{/if}
					</div>

					<div>
						<h3 class="mb-3 text-sm font-semibold uppercase tracking-[0.15em] text-amber-100">{$t.game.profile.myFriends}</h3>
						{#if friends.length === 0}
							<p class="text-sm text-slate-400">{$t.game.profile.noFriends}</p>
						{:else}
							<div class="space-y-3">
								{#each friends as friend (friend.id)}
									<div class="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-white/10 bg-white/5 px-4 py-3">
										<div>
											<p class="font-semibold text-white">{friend.friendName}</p>
												<p class="text-xs text-slate-400">@{friend.friendUsername}</p>
										</div>
										<form method="POST" action="?/removeFriend" use:enhance>
											<input type="hidden" name="friendshipId" value={friend.id} />
											<button type="submit" class="rounded-lg border border-red-500/50 bg-red-900/20 px-3 py-1.5 text-xs font-semibold text-red-300 transition hover:bg-red-900/40">{$t.game.profile.remove}</button>
										</form>
									</div>
								{/each}
							</div>
						{/if}
					</div>
				</div>
			</div>
			{/if}

			<!-- Password Tab -->
			{#if activeTab === 'password'}
			<div class="rounded-3xl border border-white/10 bg-white/5 p-6 shadow-[0_24px_60px_rgba(0,0,0,0.45)] backdrop-blur sm:p-8">
				<h2 class="mb-6 text-2xl font-bold uppercase tracking-[0.2em] text-amber-50">
					{$t.game.profile.changePasswordTitle}
				</h2>

				<!-- Form -->
				<form
					method="POST"
					action="?/changePassword"
					use:enhance={() => {
						isLoading = true;
						return async ({ update }) => {
							isLoading = false;
							oldPassword = '';
							newPassword = '';
							confirmPassword = '';
							await update();
						};
					}}
					class="space-y-6"
				>
					<!-- Old Password Field -->
					<div>
						<label for="oldPassword" class="block text-sm font-semibold uppercase tracking-[0.2em] text-amber-100">
							{$t.game.profile.currentPassword}
						</label>
						<input
							id="oldPassword"
							type="password"
							name="oldPassword"
							bind:value={oldPassword}
							required
							placeholder="••••••••"
							class="mt-3 w-full rounded-lg border border-white/10 bg-white/5 px-4 py-3 text-white placeholder-slate-500 transition focus:border-amber-300 focus:outline-none focus:ring-2 focus:ring-amber-300/30"
						/>
					</div>

					<!-- New Password Field -->
					<div>
						<label for="newPassword" class="block text-sm font-semibold uppercase tracking-[0.2em] text-amber-100">
							{$t.game.profile.newPassword}
						</label>
						<input
							id="newPassword"
							type="password"
							name="newPassword"
							bind:value={newPassword}
							required
							placeholder="••••••••"
							class="mt-3 w-full rounded-lg border border-white/10 bg-white/5 px-4 py-3 text-white placeholder-slate-500 transition focus:border-amber-300 focus:outline-none focus:ring-2 focus:ring-amber-300/30"
						/>
					</div>

					<!-- Confirm Password Field -->
					<div>
						<label for="confirmPassword" class="block text-sm font-semibold uppercase tracking-[0.2em] text-amber-100">
							{$t.game.profile.confirmPassword}
						</label>
						<input
							id="confirmPassword"
							type="password"
							name="confirmPassword"
							bind:value={confirmPassword}
							required
							placeholder="••••••••"
							class="mt-3 w-full rounded-lg border border-white/10 bg-white/5 px-4 py-3 text-white placeholder-slate-500 transition focus:border-amber-300 focus:outline-none focus:ring-2 focus:ring-amber-300/30"
						/>
					</div>

					<!-- Error Message -->
					{#if form && form.message && form.success !== true}
						<div class="rounded-lg border border-red-500/30 bg-red-900/20 px-4 py-3 text-sm text-red-200">
							{form.message}
						</div>
					{/if}

					<!-- Success Message -->
					{#if showSuccess}
						<div class="rounded-lg border border-green-500/30 bg-green-900/20 px-4 py-3 text-sm text-green-200">
							{$t.game.profile.passwordChangeSuccess}
						</div>
					{/if}

					<!-- Submit Button -->
					<button
						type="submit"
						disabled={isLoading}
						class="w-full rounded-full bg-amber-300 px-6 py-3 text-sm font-semibold text-slate-900 transition disabled:opacity-50 hover:bg-amber-200"
					>
						{isLoading ? $t.game.profile.changing : $t.game.profile.changePassword}
					</button>
				</form>
			</div>
			{/if}

			<!-- Daily History Tab -->
			{#if activeTab === 'daily'}
			<div class="rounded-3xl border border-white/10 bg-white/5 p-6 shadow-[0_24px_60px_rgba(0,0,0,0.45)] backdrop-blur sm:p-8">
				<h2 class="mb-6 text-2xl font-bold uppercase tracking-[0.2em] text-amber-50">
					{$t.game.profile.dailyHistoryTitle}
				</h2>

				{#if dailyHistory.length === 0}
					<p class="text-center text-slate-400">{$t.game.profile.noDailyHistory}</p>
				{:else}
					<div class="space-y-4">
						{#each dailyHistory as day (day.id)}
							<div class="flex items-center gap-4 rounded-lg border border-white/10 bg-white/5 p-4">
								<!-- Character Image -->
								<div class="shrink-0">
									{#if day.characterImage}
										<img
											src={day.characterImage}
											alt={day.characterName}
											class="h-16 w-16 rounded-lg border border-white/20 object-cover"
										/>
									{:else}
										<div class="flex h-16 w-16 items-center justify-center rounded-lg border border-white/20 bg-slate-700">
											<span class="text-xs text-slate-400">{$t.game.profile.noImage}</span>
										</div>
									{/if}
								</div>

								<!-- Character Info -->
								<div class="flex-1">
									<p class="font-semibold text-white">{day.characterName}</p>
									<p class="text-xs text-slate-400">
										{new Date(day.date).toLocaleDateString($language === 'fr' ? 'fr-FR' : 'en-US', {
											year: 'numeric',
											month: 'long',
											day: 'numeric'
										})}
									</p>
									<div class="mt-3">
										<p class="text-[11px] font-semibold uppercase tracking-[0.2em] text-amber-100">
											{$t.game.profile.triedCharactersTitle}
										</p>
										{#if day.triedCharacters && day.triedCharacters.length > 0}
											<div class="mt-2 flex flex-wrap gap-2">
												{#each day.triedCharacters as triedCharacter (triedCharacter.id)}
													<span class="inline-flex items-center gap-2 rounded-full border border-white/15 bg-white/5 px-2.5 py-1 text-xs text-slate-200">
														{#if triedCharacter.pictureUrl}
															<img
																src={triedCharacter.pictureUrl}
																alt={triedCharacter.name}
																class="h-4 w-4 rounded-full object-cover"
															/>
														{/if}
														{triedCharacter.name}
													</span>
												{/each}
											</div>
										{:else}
											<p class="mt-1 text-xs text-slate-500">{$t.game.profile.noTriedCharacters}</p>
										{/if}
									</div>
								</div>

								<!-- Tries -->
								<div class="flex flex-col items-end">
									<p class="text-xs text-slate-400">
										{day.tryCount} {day.tryCount === 1 ? $t.game.profile.trySingular : $t.game.profile.tryPlural}
									</p>
								</div>
							</div>
						{/each}
					</div>
				{/if}
			</div>
			{/if}

			<!-- Sessions Tab -->
			{#if activeTab === 'sessions'}
			<div class="rounded-3xl border border-white/10 bg-white/5 p-6 shadow-[0_24px_60px_rgba(0,0,0,0.45)] backdrop-blur sm:p-8">
				<h2 class="mb-6 text-2xl font-bold uppercase tracking-[0.2em] text-amber-50">
					{$t.game.profile.activeSessionsTitle}
				</h2>

				{#if sessions.length === 0}
					<p class="text-center text-slate-400">{$t.game.profile.noActiveSessions}</p>
				{:else}
					<div class="space-y-4">
						{#each sessions as sess (sess.id)}
							<div class="flex items-center justify-between rounded-lg border border-white/10 bg-white/5 px-4 py-4">
								<div class="flex-1">
									<p class="font-semibold text-white">
										{sess.userAgent || $t.game.profile.unknownDevice}
									</p>
									<p class="text-xs text-slate-400">
										{$t.game.profile.ip}: {sess.ipAddress || $t.game.profile.unknown}
									</p>
									<p class="mt-1 text-xs text-slate-500">
										{$t.game.profile.created}: {new Date(sess.createdAt).toLocaleDateString($language === 'fr' ? 'fr-FR' : 'en-US', {
											year: 'numeric',
											month: 'long',
											day: 'numeric',
											hour: '2-digit',
											minute: '2-digit'
										})}
									</p>
								</div>
								<form
									method="POST"
									action="?/revokeSession"
									style="display: inline;"
									use:enhance={() => {
										return async ({ update }) => {
											await update();
										};
									}}
								>
									<input type="hidden" name="sessionId" value={sess.id} />
									<button
										type="submit"
										class="rounded-lg border border-red-500/50 bg-red-900/20 px-4 py-2 text-xs font-semibold text-red-300 transition hover:border-red-500 hover:bg-red-900/40"
									>
										{$t.game.profile.terminate}
									</button>
								</form>
							</div>
						{/each}
					</div>
				{/if}
			</div>
			{/if}

			<!-- Back to Home -->
			<div class="text-center">
				<a href={resolve("/")} class="text-sm text-slate-400 transition hover:text-slate-300">
					← {$t.game.profile.backHome}
				</a>
			</div>
		</div>
	</div>
</main>
