<script lang="ts">
	import { enhance } from '$app/forms';
	import AppShell from '$lib/components/layout/AppShell.svelte';
	import MemberAvatar from '$lib/components/profil/MemberAvatar.svelte';
	import ProfileForm from '$lib/components/profil/ProfileForm.svelte';
	import ProfileTabButton from '$lib/components/profil/ProfileTabButton.svelte';
	import ProfileTabHeader from '$lib/components/profil/ProfileTabHeader.svelte';
	import WarungForm from '$lib/components/profil/WarungForm.svelte';
	import FlashToast from '$lib/components/ui/FlashToast.svelte';
	import OutlineIcon from '$lib/components/ui/OutlineIcon.svelte';
	import type { OutlineIconName } from '$lib/components/ui/OutlineIcon.svelte';
	import type { ActionData, PageData } from './$types';

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

	const wf = form?.warungValues ?? data.warungForm;

	type ProfileTab = 'profil' | 'warung' | 'password';

	const tabs: { id: ProfileTab; label: string; icon: OutlineIconName }[] = [
		{ id: 'profil', label: 'Akun', icon: 'user' },
		{ id: 'warung', label: 'Warung', icon: 'store' },
		{ id: 'password', label: 'Password', icon: 'lock' }
	];

	let activeTab = $state<ProfileTab>('profil');
	let profilLoading = $state(false);
	let warungLoading = $state(false);
	let passwordLoading = $state(false);
	let showPasswordLama = $state(false);
	let showPasswordBaru = $state(false);
	let showKonfirmasi = $state(false);

	let nama = $state(form?.values?.nama ?? data.profil.nama);
	let email = $state(form?.values?.email ?? data.profil.email);

	let warung_nama = $state(wf.nama);
	let deskripsi = $state(wf.deskripsi);
	let kategori = $state(wf.kategori);
	let alamat = $state(wf.alamat);
	let kelurahan = $state(wf.kelurahan);
	let kecamatan = $state(wf.kecamatan);
	let kota = $state(wf.kota);
	let provinsi = $state(wf.provinsi);
	let kode_pos = $state(wf.kode_pos);
	let telepon = $state(wf.telepon);
	let whatsapp = $state(wf.whatsapp);
	let latitude = $state(wf.latitude);
	let longitude = $state(wf.longitude);
	let jam_buka = $state(wf.jam_buka);
	let jam_tutup = $state(wf.jam_tutup);
	let hari_buka = $state(wf.hari_buka);
	let hari_buka_kode = $state(wf.hari_buka_kode);
	let kodepos_id = $state(wf.kodepos_id);
	let foto_url = $state(wf.foto_url);
	let is_aktif = $state(wf.is_aktif);
	let is_publik = $state(wf.is_publik);
	let mode_inventori = $state(wf.mode_inventori);

	const tanggalBergabung = new Date(data.profil.created_at).toLocaleDateString('id-ID', {
		day: 'numeric',
		month: 'long',
		year: 'numeric'
	});
</script>

<svelte:head>
	<title>Profil — Catatan Warung</title>
</svelte:head>

<FlashToast message={data.profilUpdated ? 'Profil akun berhasil diperbarui!' : undefined} />
<FlashToast message={data.warungUpdated ? 'Data warung berhasil disimpan!' : undefined} />
<FlashToast message={data.passwordUpdated ? 'Password berhasil diubah!' : undefined} />
<FlashToast message={form?.passwordError} type="error" />

<AppShell memberName={data.member.nama} memberEmail={data.member.email}>
	<header
		class="relative overflow-hidden bg-gradient-to-br from-violet-600 via-purple-600 to-indigo-700 px-5 pb-8 pr-20 pt-[max(1.25rem,env(safe-area-inset-top))] text-white lg:hidden"
	>
		<div class="pointer-events-none absolute -right-10 -top-10 h-40 w-40 rounded-full bg-white/10 blur-3xl"></div>
		<h1 class="text-xl font-bold">Profil Saya</h1>
		<p class="text-sm text-white/70">Kelola akun & data warung</p>

		<div class="relative z-10 mt-6 flex items-center gap-4">
			<MemberAvatar
				nama={data.profil.nama}
				avatarUrl={data.profil.avatar_url}
				size="lg"
				variant="on-dark"
			/>
			<div class="min-w-0 flex-1">
				<p class="truncate text-xl font-bold">{data.profil.nama}</p>
				<p class="truncate text-sm text-white/70">{data.warung?.nama || 'Warung belum didaftarkan'}</p>
				<p class="mt-1 text-xs text-white/50">Member sejak {tanggalBergabung}</p>
			</div>
		</div>
	</header>

	<header class="desktop-page-header">
		<div class="flex items-center gap-4">
			<MemberAvatar nama={data.profil.nama} avatarUrl={data.profil.avatar_url} size="xl" />
			<div>
				<h1 class="text-2xl font-bold">Profil & Pengaturan</h1>
				<p class="text-sm text-base-content/50">Kelola akun, data warung, dan keamanan</p>
			</div>
		</div>
		<a href="/langganan" class="badge badge-lg badge-secondary gap-2">
			<OutlineIcon name="paket" size="xs" />
			Paket {data.entitlements?.paketNama ?? 'Free'}
		</a>
	</header>

	<main class="page-content">
		<div class="tabs tabs-boxed overflow-x-auto bg-base-200 p-1 lg:hidden">
			{#each tabs as tab}
				<ProfileTabButton
					label={tab.label}
					icon={tab.icon}
					active={activeTab === tab.id}
					onclick={() => (activeTab = tab.id)}
				/>
			{/each}
		</div>

		<div class="hidden gap-2 lg:flex">
			{#each tabs as tab}
				<ProfileTabButton
					label={tab.label}
					icon={tab.icon}
					active={activeTab === tab.id}
					variant="desktop"
					onclick={() => (activeTab = tab.id)}
				/>
			{/each}
		</div>

		{#if activeTab === 'profil'}
			<ProfileForm
				bind:nama
				bind:email
				avatarUrl={data.profil.avatar_url}
				namaWarung={data.warung?.nama}
				error={form?.profilError}
				bind:loading={profilLoading}
			/>
		{/if}

		{#if activeTab === 'warung'}
			<WarungForm
				kategoriList={data.referensi.kategori}
				hariBukaList={data.referensi.hariBuka}
				kodeposReady={data.referensi.kodeposReady}
				bind:nama={warung_nama}
				bind:deskripsi
				bind:kategori
				bind:alamat
				bind:kelurahan
				bind:kecamatan
				bind:kota
				bind:provinsi
				bind:kode_pos
				bind:telepon
				bind:whatsapp
				bind:latitude
				bind:longitude
				bind:jam_buka
				bind:jam_tutup
				bind:hari_buka
				bind:hari_buka_kode
				bind:kodepos_id
				bind:foto_url
				bind:is_aktif
				bind:is_publik
				bind:mode_inventori
				canInventoriStok={data.canInventoriStok}
				canWarungPublik={data.canWarungPublik}
				error={form?.warungError}
				bind:loading={warungLoading}
			/>
		{/if}

		{#if activeTab === 'password'}
			<section class="flex max-w-xl flex-col gap-5">
				<ProfileTabHeader
					title="Keamanan Akun"
					subtitle="Ubah password untuk menjaga keamanan"
					icon="lock"
					tone="rose"
				/>

				<form
					method="POST"
					action="?/updatePassword"
					class="flex flex-col gap-4"
					use:enhance={() => {
						passwordLoading = true;
						return async ({ update }) => {
							passwordLoading = false;
							await update();
						};
					}}
				>
					<div class="form-control">
						<label class="label" for="password_lama"><span class="label-text font-semibold">Password Lama</span></label>
						<label class="input input-bordered flex items-center gap-2 rounded-xl">
							<input
								id="password_lama"
								name="password_lama"
								type={showPasswordLama ? 'text' : 'password'}
								class="grow"
								required
								autocomplete="current-password"
							/>
							<button type="button" class="btn btn-ghost btn-xs" onclick={() => (showPasswordLama = !showPasswordLama)}>
								{showPasswordLama ? 'Sembunyikan' : 'Tampilkan'}
							</button>
						</label>
					</div>
					<div class="form-control">
						<label class="label" for="password_baru"><span class="label-text font-semibold">Password Baru</span></label>
						<label class="input input-bordered flex items-center gap-2 rounded-xl">
							<input
								id="password_baru"
								name="password_baru"
								type={showPasswordBaru ? 'text' : 'password'}
								class="grow"
								required
								minlength="6"
								autocomplete="new-password"
							/>
							<button type="button" class="btn btn-ghost btn-xs" onclick={() => (showPasswordBaru = !showPasswordBaru)}>
								{showPasswordBaru ? 'Sembunyikan' : 'Tampilkan'}
							</button>
						</label>
					</div>
					<div class="form-control">
						<label class="label" for="konfirmasi"><span class="label-text font-semibold">Konfirmasi Password</span></label>
						<label class="input input-bordered flex items-center gap-2 rounded-xl">
							<input
								id="konfirmasi"
								name="konfirmasi"
								type={showKonfirmasi ? 'text' : 'password'}
								class="grow"
								required
								minlength="6"
								autocomplete="new-password"
							/>
							<button type="button" class="btn btn-ghost btn-xs" onclick={() => (showKonfirmasi = !showKonfirmasi)}>
								{showKonfirmasi ? 'Sembunyikan' : 'Tampilkan'}
							</button>
						</label>
					</div>
					<button type="submit" class="btn btn-outline btn-error gap-1.5 rounded-xl" disabled={passwordLoading}>
						<OutlineIcon name="lock" size="xs" />
						{passwordLoading ? 'Memproses...' : 'Ubah Password'}
					</button>
				</form>
			</section>
		{/if}
	</main>
</AppShell>
