<script lang="ts">
	import { enhance } from '$app/forms';
	import { confirmBeforeSubmit } from '$lib/utils/confirm';
	import type { ActionData, PageData } from './$types';
	import type { LandingItem, LandingItemTipe } from '$lib/types/landing';

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

	let activeTab = $state<'teks' | 'item'>('teks');
	let activeItemType = $state<LandingItemTipe>('feature');
	let editingItem = $state<LandingItem | null>(null);

	const itemsByType = $derived(
		data.items.filter((item) => item.tipe === activeItemType).sort((a, b) => a.urutan - b.urutan)
	);

	function startEdit(item: LandingItem) {
		editingItem = { ...item };
	}

	function startAdd() {
		editingItem = {
			id: 0,
			tipe: activeItemType,
			urutan: itemsByType.length + 1,
			judul: '',
			deskripsi: '',
			icon: activeItemType === 'feature' ? '✨' : null,
			warna: activeItemType === 'feature' ? 'from-emerald-500 to-teal-600' : null,
			is_aktif: true
		};
	}

	function cancelEdit() {
		editingItem = null;
	}

	function itemLabel(tipe: LandingItemTipe): string {
		return data.itemTypes.find((t) => t.tipe === tipe)?.label ?? tipe;
	}
</script>

<svelte:head>
	<title>Back Office — Landing Page</title>
</svelte:head>

<div class="page-content">
	<div class="flex flex-wrap items-start justify-between gap-4">
		<div>
			<h1 class="text-2xl font-bold">Kelola Landing Page</h1>
			<p class="text-sm text-base-content/50">
				Ubah teks, fitur, FAQ, dan konten lain di halaman depan tanpa deploy ulang.
			</p>
		</div>
		<a href="/" target="_blank" rel="noopener noreferrer" class="btn btn-outline btn-sm gap-2">
			👁️ Lihat Landing Page
		</a>
	</div>

	{#if form?.success}
		<div class="alert alert-success mt-4">
			<span>✅ {form.message}</span>
		</div>
	{/if}
	{#if form?.error}
		<div class="alert alert-error mt-4">
			<span>{form.error}</span>
		</div>
	{/if}

	<div role="tablist" class="tabs tabs-boxed mt-6 w-fit bg-base-200">
		<button
			type="button"
			role="tab"
			class="tab {activeTab === 'teks' ? 'tab-active' : ''}"
			onclick={() => (activeTab = 'teks')}
		>
			📝 Teks & Judul
		</button>
		<button
			type="button"
			role="tab"
			class="tab {activeTab === 'item' ? 'tab-active' : ''}"
			onclick={() => (activeTab = 'item')}
		>
			📋 Item (Fitur, FAQ, dll)
		</button>
	</div>

	{#if activeTab === 'teks'}
		<div class="mt-6 max-w-3xl space-y-6">
			{#each data.kontenGroups as group}
				<div class="card bg-base-100 shadow-md">
					<div class="card-body gap-6">
						<div class="border-b border-base-300/60 pb-3">
							<h2 class="text-lg font-bold">{group.label}</h2>
							<p class="mt-1 text-sm text-base-content/50">Isi tiap field lalu simpan bagian ini.</p>
						</div>
						<form method="POST" action="?/saveKonten" use:enhance class="space-y-5">
							<input type="hidden" name="group_id" value={group.id} />
							{#each group.fields as field}
								<div class="flex flex-col gap-2">
									<label for="konten-{group.id}-{field.key}" class="text-sm font-semibold text-base-content">
										{field.label}
									</label>
									{#if field.type === 'textarea'}
										<textarea
											id="konten-{group.id}-{field.key}"
											name={field.key}
											class="textarea textarea-bordered w-full"
											rows="3"
										>{data.konten[field.key] ?? ''}</textarea>
									{:else}
										<input
											id="konten-{group.id}-{field.key}"
											type="text"
											name={field.key}
											class="input input-bordered w-full"
											value={data.konten[field.key] ?? ''}
										/>
									{/if}
								</div>
							{/each}
							<div class="border-t border-base-300/60 pt-4">
								<button type="submit" class="btn btn-primary">Simpan {group.label}</button>
							</div>
						</form>
					</div>
				</div>
			{/each}
		</div>
	{:else}
		<div class="mt-6 flex flex-wrap gap-2">
			{#each data.itemTypes as type}
				<button
					type="button"
					class="btn btn-sm {activeItemType === type.tipe ? 'btn-primary' : 'btn-ghost'}"
					onclick={() => {
						activeItemType = type.tipe;
						editingItem = null;
					}}
				>
					{type.icon} {type.label}
				</button>
			{/each}
		</div>

		<div class="mt-4 flex justify-end">
			<button type="button" class="btn btn-primary btn-sm" onclick={startAdd}>
				+ Tambah {itemLabel(activeItemType)}
			</button>
		</div>

		{#if editingItem}
			<div class="card mt-4 max-w-3xl border-2 border-primary/30 bg-base-100 shadow-lg">
				<div class="card-body gap-6">
					<div class="border-b border-base-300/60 pb-3">
						<h3 class="text-lg font-bold">
							{editingItem.id ? 'Edit' : 'Tambah'} {itemLabel(activeItemType)}
						</h3>
					</div>
					<form method="POST" action="?/saveItem" use:enhance class="space-y-5">
						<input type="hidden" name="id" value={editingItem.id || ''} />
						<input type="hidden" name="tipe" value={activeItemType} />

						<div class="flex flex-col gap-2">
							<label for="item-urutan" class="text-sm font-semibold text-base-content">Urutan</label>
							<input
								id="item-urutan"
								type="number"
								name="urutan"
								class="input input-bordered w-full max-w-xs"
								min="0"
								bind:value={editingItem.urutan}
								required
							/>
							<p class="text-xs text-base-content/50">Angka lebih kecil tampil lebih dulu.</p>
						</div>

						<div class="flex flex-col gap-2">
							<span class="text-sm font-semibold text-base-content">Status</span>
							<label class="flex items-center gap-3 rounded-xl border border-base-300 bg-base-200/40 px-4 py-3">
								<input
									type="checkbox"
									name="is_aktif"
									value="1"
									class="toggle toggle-primary"
									bind:checked={editingItem.is_aktif}
								/>
								<span class="text-sm">Tampilkan di landing page</span>
							</label>
						</div>

						<div class="flex flex-col gap-2">
							<label for="item-judul" class="text-sm font-semibold text-base-content">
								{activeItemType === 'faq'
									? 'Pertanyaan'
									: activeItemType === 'stat'
										? 'Nilai / Angka'
										: 'Judul'}
							</label>
							<input
								id="item-judul"
								type="text"
								name="judul"
								class="input input-bordered w-full"
								bind:value={editingItem.judul}
								required
							/>
						</div>

						{#if activeItemType !== 'mobile_highlight'}
							<div class="flex flex-col gap-2">
								<label for="item-deskripsi" class="text-sm font-semibold text-base-content">
									{activeItemType === 'faq'
										? 'Jawaban'
										: activeItemType === 'stat'
											? 'Label'
											: 'Deskripsi'}
								</label>
								<textarea
									id="item-deskripsi"
									name="deskripsi"
									class="textarea textarea-bordered w-full"
									rows="3"
									bind:value={editingItem.deskripsi}
								></textarea>
							</div>
						{:else}
							<input type="hidden" name="deskripsi" value="" />
						{/if}

						{#if activeItemType === 'feature'}
							<div class="flex flex-col gap-2">
								<label for="item-icon" class="text-sm font-semibold text-base-content">Icon (emoji)</label>
								<input
									id="item-icon"
									type="text"
									name="icon"
									class="input input-bordered w-full max-w-xs"
									bind:value={editingItem.icon}
									placeholder="💰"
								/>
							</div>
							<div class="flex flex-col gap-2">
								<label for="item-warna" class="text-sm font-semibold text-base-content">
									Warna gradient (Tailwind)
								</label>
								<input
									id="item-warna"
									type="text"
									name="warna"
									class="input input-bordered w-full"
									bind:value={editingItem.warna}
									placeholder="from-emerald-500 to-teal-600"
								/>
								<p class="text-xs text-base-content/50">Contoh: from-emerald-500 to-teal-600</p>
							</div>
						{:else}
							<input type="hidden" name="icon" value="" />
							<input type="hidden" name="warna" value="" />
						{/if}

						<div class="flex gap-2 border-t border-base-300/60 pt-4">
							<button type="submit" class="btn btn-primary">Simpan</button>
							<button type="button" class="btn btn-ghost" onclick={cancelEdit}>Batal</button>
						</div>
					</form>
				</div>
			</div>
		{/if}

		<div class="mt-6 max-w-3xl space-y-3">
			{#each itemsByType as item (item.id)}
				<div
					class="card border bg-base-100 shadow-sm {item.is_aktif ? '' : 'opacity-60'}"
				>
					<div class="card-body flex-row flex-wrap items-center justify-between gap-4 p-4">
						<div class="min-w-0 flex-1">
							<div class="flex flex-wrap items-center gap-2">
								<span class="badge badge-outline badge-sm">#{item.urutan}</span>
								{#if item.icon}
									<span class="text-xl">{item.icon}</span>
								{/if}
								{#if !item.is_aktif}
									<span class="badge badge-warning badge-sm">Nonaktif</span>
								{/if}
							</div>
							<p class="mt-1 font-semibold">{item.judul}</p>
							{#if item.deskripsi}
								<p class="mt-1 text-sm text-base-content/60 line-clamp-2">{item.deskripsi}</p>
							{/if}
							{#if item.warna}
								<p class="mt-1 text-xs text-base-content/40">{item.warna}</p>
							{/if}
						</div>
						<div class="flex shrink-0 flex-wrap gap-2">
							<button type="button" class="btn btn-ghost btn-sm" onclick={() => startEdit(item)}>
								Edit
							</button>
							<form method="POST" action="?/toggleItem" use:enhance>
								<input type="hidden" name="id" value={item.id} />
								<input type="hidden" name="is_aktif" value={item.is_aktif ? '0' : '1'} />
								<button type="submit" class="btn btn-ghost btn-sm">
									{item.is_aktif ? 'Sembunyikan' : 'Aktifkan'}
								</button>
							</form>
							<form method="POST" action="?/deleteItem" use:enhance>
								<input type="hidden" name="id" value={item.id} />
								<button
									type="submit"
									class="btn btn-ghost btn-sm text-error"
									onclick={(e) =>
										confirmBeforeSubmit(e, {
											title: 'Hapus Item',
											message: 'Item landing ini akan dihapus permanen. Lanjutkan?',
											confirmText: 'Hapus',
											tone: 'danger'
										})}
								>
									Hapus
								</button>
							</form>
						</div>
					</div>
				</div>
			{:else}
				<div class="rounded-xl border border-dashed border-base-300 p-8 text-center text-base-content/50">
					Belum ada item. Klik "Tambah" untuk menambahkan.
				</div>
			{/each}
		</div>
	{/if}
</div>
