<script lang="ts">
	import { enhance } from '$app/forms';
	import MemberAvatar from '$lib/components/profil/MemberAvatar.svelte';
	import ProfileTabHeader from '$lib/components/profil/ProfileTabHeader.svelte';
	import FlashToast from '$lib/components/ui/FlashToast.svelte';
	import OutlineIcon from '$lib/components/ui/OutlineIcon.svelte';
	import { AVATAR_ACCEPT, AVATAR_MAX_BYTES } from '$lib/constants/avatar';

	interface Props {
		nama: string;
		email: string;
		avatarUrl?: string | null;
		namaWarung?: string;
		error?: string;
		loading?: boolean;
	}

	let {
		nama = $bindable(),
		email = $bindable(),
		avatarUrl = null,
		namaWarung = '',
		error,
		loading = $bindable(false)
	}: Props = $props();

	let avatarPreview = $state<string | null>(null);
	let avatarError = $state<string | null>(null);
	let fileInput: HTMLInputElement | undefined = $state();

	const displayAvatar = $derived(avatarPreview ?? avatarUrl);

	function handleAvatarChange(event: Event) {
		const input = event.currentTarget as HTMLInputElement;
		const file = input.files?.[0];
		avatarError = null;

		if (!file) {
			avatarPreview = null;
			return;
		}

		if (file.size > AVATAR_MAX_BYTES) {
			avatarError = 'Ukuran gambar maksimal 1 MB.';
			input.value = '';
			avatarPreview = null;
			return;
		}

		if (!['image/jpeg', 'image/png', 'image/webp', 'image/gif'].includes(file.type)) {
			avatarError = 'Format harus JPG, PNG, WEBP, atau GIF.';
			input.value = '';
			avatarPreview = null;
			return;
		}

		avatarPreview = URL.createObjectURL(file);
	}
</script>

<section class="flex max-w-xl flex-col gap-5">
	<ProfileTabHeader
		title="Informasi Akun"
		subtitle="Data login & identitas pemilik"
		icon="user"
		tone="violet"
	/>

	<FlashToast message={error} type="error" />

	<form
		method="POST"
		action="?/updateProfil"
		enctype="multipart/form-data"
		class="flex flex-col gap-4"
		use:enhance={() => {
			loading = true;
			return async ({ update }) => {
				loading = false;
				await update();
			};
		}}
	>
		<div class="form-control">
			<label class="label" for="avatar">
				<span class="label-text font-semibold">Foto Profil</span>
			</label>
			<div class="flex items-center gap-4">
				<MemberAvatar nama={nama} avatarUrl={displayAvatar} size="lg" />
				<div class="min-w-0 flex-1">
					<p class="truncate text-sm font-semibold">{nama || 'Nama belum diisi'}</p>
					<p class="truncate text-sm text-base-content/50">{email || 'Email belum diisi'}</p>
					{#if namaWarung}
						<p class="truncate text-sm text-base-content/50">{namaWarung}</p>
					{/if}
					<button
						type="button"
						class="btn btn-outline btn-sm mt-2 gap-1.5 rounded-xl"
						onclick={() => fileInput?.click()}
					>
						<OutlineIcon name="edit" size="xs" />
						Ubah Foto
					</button>
					<p class="mt-1 text-sm text-base-content/50">JPG, PNG, WEBP, GIF · maks. 1 MB</p>
					{#if avatarError}
						<p class="mt-1 text-sm text-error">{avatarError}</p>
					{/if}
				</div>
			</div>
			<input
				bind:this={fileInput}
				id="avatar"
				type="file"
				name="avatar"
				accept={AVATAR_ACCEPT}
				class="hidden"
				onchange={handleAvatarChange}
			/>
		</div>

		<div class="form-control">
			<label class="label" for="nama">
				<span class="label-text font-semibold">Nama Lengkap</span>
			</label>
			<input
				id="nama"
				name="nama"
				type="text"
				class="input input-bordered w-full rounded-xl"
				bind:value={nama}
				required
				maxlength="100"
			/>
		</div>

		<div class="form-control">
			<label class="label" for="email">
				<span class="label-text font-semibold">Alamat Email</span>
			</label>
			<input
				id="email"
				name="email"
				type="email"
				class="input input-bordered w-full rounded-xl"
				bind:value={email}
				required
			/>
		</div>

		<button type="submit" class="btn btn-outline btn-primary gap-1.5 rounded-xl" disabled={loading}>
			<OutlineIcon name="user" size="xs" />
			{loading ? 'Menyimpan...' : 'Simpan Akun'}
		</button>
	</form>
</section>
