<script lang="ts">
	import { onMount } from 'svelte';
	import Icon from '@iconify/svelte';
	import type { Profile } from '$lib/eve';
	import { nip19 } from 'nostr-tools';
	import ArxletHeader from '$lib/components/ArxletHeader.svelte';
	import Input from '$lib/components/PublicComponents/Input.svelte';
	import Textarea from '$lib/components/PublicComponents/Textarea.svelte';

	let profile: Profile = $state({
		name: '',
		about: '',
		picture: ''
	});

	let isLoading = $state(true);
	let isSaving = $state(false);
	let saveMessage = $state('');
	let publicKey = $state('');

	onMount(async () => {
		try {
			publicKey = await window.eve.getPublicKey();
			const userProfile = await window.eve.getProfile(publicKey);
			if (userProfile) {
				profile = { ...userProfile };
			}
		} catch (error) {
			console.error('Error loading profile:', error);
		} finally {
			isLoading = false;
		}
	});

	async function handleSave() {
		isSaving = true;
		saveMessage = '';

		try {
			const event = await window.eve.signEvent({
				kind: 0,
				pubkey: publicKey,
				content: JSON.stringify(profile),
				tags: [],
				created_at: Math.floor(Date.now() / 1000)
			});
			await window.eve.publish(event);
			saveMessage = 'Profile saved successfully!';

			window.dispatchEvent(
				new CustomEvent('profileUpdated', {
					detail: {
						publicKey,
						avatarUrl: profile.picture || window.eve.getAvatar(publicKey)
					}
				})
			);

			setTimeout(() => (saveMessage = ''), 3000);
		} catch (error) {
			console.error('Error saving profile:', error);
			saveMessage = 'Error saving profile. Please try again.';
		} finally {
			isSaving = false;
		}
	}

	function resetChanges() {
		window.location.reload();
	}
</script>

<svelte:head>
	<title>Profile - EVE</title>
</svelte:head>

<ArxletHeader
	title="Edit Profile"
	subtitle="Update your profile information"
	icon="mdi:user"
	iconColor="#3f00dd"
/>

<div class="max-w-2xl mx-auto px-4 py-6">
	{#if isLoading}
		<div class="flex justify-center items-center py-12">
			<span class="loading loading-spinner loading-lg" />
		</div>
	{:else}
		<form on:submit|preventDefault={handleSave} class="space-y-6">
			<div class="bg-base-100 rounded-lg border border-base-300 shadow-sm overflow-hidden">
				<div class="px-6 py-4 border-b border-base-200 bg-base-50">
					<div class="flex items-center gap-3">
						<Icon icon="mdi:account-circle" class="w-5 h-5 text-primary" />
						<h3 class="text-lg font-medium text-base-content">Profile Picture</h3>
					</div>
				</div>

				<div class="p-6">
					<div class="flex items-start gap-6">
						<div class="flex-shrink-0">
							<div class="avatar">
								<div
									class="w-20 h-20 rounded-full ring-2 ring-base-300 ring-offset-2 ring-offset-base-100"
								>
									{#if profile.picture}
										<img
											src={profile.picture}
											alt="Profile avatar"
											class="object-cover w-full h-full rounded-full"
										/>
									{:else}
										<img
											src={window.eve?.getAvatar?.(publicKey) || ''}
											alt="Default avatar"
											class="object-cover w-full h-full rounded-full"
										/>
									{/if}
								</div>
							</div>
						</div>

						<Input
							label="Avatar URL"
							placeholder="https://example.com/avatar.jpg"
							bind:value={profile.picture}
						>
							<p class="mt-1 text-xs text-base-content/60">
								Enter a direct link to your profile image
							</p>
						</Input>
					</div>
				</div>
			</div>

			<div
				class="bg-base-100 rounded-lg border border-base-300 shadow-sm overflow-hidden px-6 py-4"
			>
				<div class="flex items-center gap-3">
					<Icon icon="mdi:card-account-details" class="w-5 h-5 text-primary" />
					<h3 class="text-lg font-medium text-base-content">Basic Information</h3>
				</div>

				<Input
					label="Display Name"
					placeholder="Enter your display name"
					bind:value={profile.name!}
				>
					<p class="text-xs text-base-content/60">This is how others will see your name</p>
				</Input>

				<Textarea
					label="About"
					bind:value={profile.about!}
					placeholder="Tell others about yourself"
					rows="4"
				>
					<p class="text-xs text-base-content/60">
						Share your interests, background, or anything you'd like others to know
					</p>
				</Textarea>
			</div>

			<div class="bg-base-100 rounded-lg border border-base-300 shadow-sm overflow-hidden">
				<div class="px-6 py-4 border-b border-base-200 bg-base-50">
					<div class="flex items-center gap-3">
						<Icon icon="mdi:key-variant" class="w-5 h-5 text-primary" />
						<h3 class="text-lg font-medium text-base-content">Identity</h3>
					</div>
				</div>

				<div class="px-6 py-4">
					<div class="flex flex-col gap-2">
						<label for="pubkey" class="text-sm font-medium text-base-content">Public Key</label>
						<div class="flex gap-2">
							<input
								id="pubkey"
								value={nip19.npubEncode(publicKey)}
								type="text"
								readonly
								class="flex-1 px-3 py-2 text-sm font-mono border border-base-300 rounded-md bg-base-50 text-base-content/70"
							/>
							<button
								type="button"
								class="px-3 py-2 text-sm border border-base-300 rounded-md bg-base-100 hover:bg-base-200 transition-colors flex items-center gap-2"
								on:click={() => navigator.clipboard?.writeText(nip19.npubEncode(publicKey))}
								title="Copy to clipboard"
							>
								<Icon icon="mdi:content-copy" class="w-4 h-4" />
							</button>
						</div>
						<p class="text-xs text-base-content/60">
							This is your unique identifier that others can use to find you
						</p>
					</div>
				</div>
			</div>

			{#if saveMessage}
				<div
					class="px-4 py-3 rounded-lg border {saveMessage.includes('Error')
						? 'bg-error/10 border-error/20 text-error'
						: 'bg-success/10 border-success/20 text-success'}"
				>
					<div class="flex items-center gap-2">
						<Icon
							icon={saveMessage.includes('Error') ? 'mdi:alert-circle' : 'mdi:check-circle'}
							class="w-4 h-4"
						/>
						<span class="text-sm font-medium">{saveMessage}</span>
					</div>
				</div>
			{/if}
		</form>

		<!-- Action Bar -->
		<div
			class="sticky bottom-0 mt-6 -mx-4 px-4 py-4 bg-base-100/80 backdrop-blur-sm border-t border-base-200"
		>
			<div class="max-w-2xl mx-auto flex gap-3">
				<button
					type="button"
					class="px-4 py-2 text-sm border border-base-300 rounded-md bg-base-100 hover:bg-base-200 transition-colors flex items-center gap-2"
					disabled={isSaving}
					on:click={resetChanges}
				>
					<Icon icon="mdi:refresh" class="w-4 h-4" />
					Reset
				</button>
				<button
					type="submit"
					class="flex-1 px-4 py-2 text-sm bg-primary text-primary-content rounded-md hover:bg-primary/90 transition-colors flex items-center justify-center gap-2 disabled:opacity-50"
					disabled={isSaving}
					form="profile-form"
					on:click={handleSave}
				>
					{#if isSaving}
						<span class="loading loading-spinner loading-sm" />
						Saving...
					{:else}
						<Icon icon="mdi:content-save" class="w-4 h-4" />
						Save Profile
					{/if}
				</button>
			</div>
		</div>
	{/if}
</div>
