<script lang="ts">
	import { enhance } from '$app/forms';
	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 type { KodeposSearchResult, RefHariBuka, RefKategoriWarung } from '$lib/types/referensi';
	import type { KategoriWarung, ModeInventori } from '$lib/types/warung';
	import { getGoogleMapsUrl } from '$lib/utils/slug';

	interface Props {
		kategoriList: RefKategoriWarung[];
		hariBukaList: RefHariBuka[];
		kodeposReady?: boolean;
		nama: string;
		deskripsi: string;
		kategori: KategoriWarung;
		alamat: string;
		kelurahan: string;
		kecamatan: string;
		kota: string;
		provinsi: string;
		kode_pos: string;
		telepon: string;
		whatsapp: string;
		latitude: string;
		longitude: string;
		jam_buka: string;
		jam_tutup: string;
		hari_buka: string;
		hari_buka_kode: string;
		kodepos_id: string;
		foto_url: string;
		is_aktif: boolean;
		is_publik: boolean;
		mode_inventori: ModeInventori;
		canInventoriStok?: boolean;
		canWarungPublik?: boolean;
		error?: string;
		loading?: boolean;
	}

	let {
		kategoriList,
		hariBukaList,
		kodeposReady = true,
		nama = $bindable(),
		deskripsi = $bindable(),
		kategori = $bindable(),
		alamat = $bindable(),
		kelurahan = $bindable(),
		kecamatan = $bindable(),
		kota = $bindable(),
		provinsi = $bindable(),
		kode_pos = $bindable(),
		telepon = $bindable(),
		whatsapp = $bindable(),
		latitude = $bindable(),
		longitude = $bindable(),
		jam_buka = $bindable(),
		jam_tutup = $bindable(),
		hari_buka = $bindable(),
		hari_buka_kode = $bindable(),
		kodepos_id = $bindable(),
		foto_url = $bindable(),
		is_aktif = $bindable(),
		is_publik = $bindable(),
		mode_inventori = $bindable(),
		canInventoriStok = true,
		canWarungPublik = true,
		error,
		loading = $bindable(false)
	}: Props = $props();

	let searchQuery = $state('');
	let searchResults = $state<KodeposSearchResult[]>([]);
	let searchLoading = $state(false);
	let searchError = $state('');
	let showResults = $state(false);
	let searchTimer: ReturnType<typeof setTimeout> | undefined;

	const wilayahTerpilih = $derived(Boolean(kodepos_id && provinsi && kota && kecamatan && kelurahan));

	const hasKoordinat = $derived(
		latitude.trim() !== '' &&
			longitude.trim() !== '' &&
			!Number.isNaN(Number(latitude)) &&
			!Number.isNaN(Number(longitude))
	);

	const mapsUrl = $derived(
		hasKoordinat ? getGoogleMapsUrl(Number(latitude), Number(longitude)) : null
	);

	const wilayahFields = $derived([
		{ id: 'wilayah_provinsi', label: 'Provinsi', value: provinsi },
		{ id: 'wilayah_kota', label: 'Kota / Kabupaten', value: kota },
		{ id: 'wilayah_kecamatan', label: 'Kecamatan', value: kecamatan },
		{ id: 'wilayah_kelurahan', label: 'Kelurahan / Desa', value: kelurahan },
		{ id: 'wilayah_kode_pos', label: 'Kode Pos', value: kode_pos, mono: true }
	]);

	function formatWilayahLabel(value: string): string {
		return value
			.toLowerCase()
			.split(' ')
			.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
			.join(' ');
	}

	function displayWilayahValue(label: string, value: string): string {
		if (!value) return '';
		return label === 'Kode Pos' ? value : formatWilayahLabel(value);
	}

	function applyWilayah(item: KodeposSearchResult) {
		kodepos_id = String(item.id);
		kelurahan = item.kelurahan;
		kecamatan = item.kecamatan;
		kota = item.kota;
		provinsi = item.provinsi;
		kode_pos = item.kode_pos;
		searchQuery = item.kelurahan;
		searchResults = [];
		showResults = false;
		searchError = '';
	}

	function clearWilayah() {
		kodepos_id = '';
		kelurahan = '';
		kecamatan = '';
		kota = '';
		provinsi = '';
		kode_pos = '';
		searchQuery = '';
		searchResults = [];
		showResults = false;
		searchError = '';
	}

	async function runSearch(query: string) {
		if (query.trim().length < 2) {
			searchResults = [];
			searchError = '';
			return;
		}

		searchLoading = true;
		searchError = '';

		try {
			const response = await fetch(`/api/referensi/cari?q=${encodeURIComponent(query.trim())}`);
			const result = await response.json();

			if (!result.success) {
				searchResults = [];
				searchError = result.message ?? 'Gagal mencari kelurahan.';
				return;
			}

			searchResults = result.data;
			if (searchResults.length === 0) {
				searchError = 'Tidak ditemukan. Coba kata kunci lain.';
			}
		} catch {
			searchResults = [];
			searchError = 'Gagal menghubungi server pencarian.';
		} finally {
			searchLoading = false;
		}
	}

	function handleSearchInput(event: Event) {
		const target = event.currentTarget as HTMLInputElement;
		searchQuery = target.value;

		if (searchTimer) clearTimeout(searchTimer);

		if (searchQuery.trim().length < 2) {
			searchResults = [];
			searchError = '';
			showResults = false;
			return;
		}

		showResults = true;
		searchTimer = setTimeout(() => runSearch(searchQuery), 350);
	}

	function handleKategoriChange(event: Event) {
		kategori = (event.currentTarget as HTMLSelectElement).value as KategoriWarung;
	}

	function handleHariBukaChange(event: Event) {
		hari_buka_kode = (event.currentTarget as HTMLSelectElement).value;
		hari_buka = hariBukaList.find((item) => item.kode === hari_buka_kode)?.label ?? '';
	}
</script>

{#snippet formField(id: string, title: string, required = false, children: import('svelte').Snippet)}
	<div class="form-control">
		<label class="label" for={id}>
			<span class="label-text font-semibold">{title}</span>
			{#if required}<span class="label-text-alt text-error">*</span>{/if}
		</label>
		{@render children()}
	</div>
{/snippet}

{#snippet groupHeading(title: string)}
	<ProfileTabHeader {title} />
{/snippet}

{#snippet fieldNama()}
	<input
		id="warung_nama"
		name="nama"
		type="text"
		class="input input-bordered w-full rounded-xl"
		placeholder="Contoh: Warung Makmur Sejahtera"
		bind:value={nama}
		required
		maxlength="150"
	/>
{/snippet}

{#snippet fieldDeskripsi()}
	<textarea
		id="deskripsi"
		name="deskripsi"
		class="textarea textarea-bordered min-h-24 w-full rounded-xl"
		placeholder="Jelaskan jenis jualan warung Anda..."
		bind:value={deskripsi}
		maxlength="1000"
	></textarea>
{/snippet}

{#snippet fieldKategori()}
	<select
		id="kategori"
		name="kategori"
		class="select select-bordered w-full max-w-none rounded-xl"
		value={kategori}
		onchange={handleKategoriChange}
		required
	>
		<option value="" disabled>Pilih kategori</option>
		{#each kategoriList as kat}
			<option value={kat.kode}>{kat.icon} {kat.nama}</option>
		{/each}
	</select>
{/snippet}

{#snippet fieldAlamat()}
	<textarea
		id="alamat"
		name="alamat"
		class="textarea textarea-bordered min-h-24 w-full rounded-xl"
		placeholder="Jl. nama jalan, nomor rumah, RT/RW, patokan..."
		bind:value={alamat}
		required
		maxlength="500"
		disabled={!kodeposReady}
	></textarea>
{/snippet}

{#snippet fieldLatitude()}
	<input
		id="latitude"
		name="latitude"
		type="text"
		inputmode="decimal"
		class="input input-bordered w-full rounded-xl font-mono text-sm"
		placeholder="-6.208800"
		bind:value={latitude}
		required
		disabled={!kodeposReady}
	/>
{/snippet}

{#snippet fieldLongitude()}
	<input
		id="longitude"
		name="longitude"
		type="text"
		inputmode="decimal"
		class="input input-bordered w-full rounded-xl font-mono text-sm"
		placeholder="106.845600"
		bind:value={longitude}
		required
		disabled={!kodeposReady}
	/>
{/snippet}

{#snippet fieldTelepon()}
	<input
		id="telepon"
		name="telepon"
		type="tel"
		class="input input-bordered w-full rounded-xl"
		placeholder="08xxxxxxxxxx"
		bind:value={telepon}
		maxlength="20"
	/>
{/snippet}

{#snippet fieldWhatsapp()}
	<input
		id="whatsapp"
		name="whatsapp"
		type="tel"
		class="input input-bordered w-full rounded-xl"
		placeholder="08xxxxxxxxxx"
		bind:value={whatsapp}
		maxlength="20"
	/>
{/snippet}

{#snippet fieldJamBuka()}
	<input
		id="jam_buka"
		name="jam_buka"
		type="time"
		class="input input-bordered w-full rounded-xl"
		bind:value={jam_buka}
	/>
{/snippet}

{#snippet fieldJamTutup()}
	<input
		id="jam_tutup"
		name="jam_tutup"
		type="time"
		class="input input-bordered w-full rounded-xl"
		bind:value={jam_tutup}
	/>
{/snippet}

{#snippet fieldHariBuka()}
	<select
		id="hari_buka_kode"
		name="hari_buka_kode"
		class="select select-bordered w-full max-w-none rounded-xl"
		value={hari_buka_kode}
		onchange={handleHariBukaChange}
		required
	>
		<option value="" disabled>Pilih hari buka</option>
		{#each hariBukaList as hari}
			<option value={hari.kode}>{hari.label}</option>
		{/each}
	</select>
{/snippet}

{#snippet fieldFotoUrl()}
	<input
		id="foto_url"
		name="foto_url"
		type="url"
		class="input input-bordered w-full rounded-xl"
		placeholder="https://contoh.com/foto-warung.jpg"
		bind:value={foto_url}
		maxlength="500"
	/>
{/snippet}

<section class="flex max-w-xl flex-col gap-5">
	<ProfileTabHeader
		title="Data Toko / Warung"
		subtitle="Lengkapi profil warung untuk CentraWarung"
		icon="store"
		tone="emerald"
	/>

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

	{#if !kodeposReady}
		<div role="alert" class="alert alert-warning">
			<span>📦</span>
			<span>Jalankan <code class="text-sm">npm run db:kodepos</code> untuk mengaktifkan pencarian wilayah.</span>
		</div>
	{/if}

	<form
		method="POST"
		action="?/updateWarung"
		class="flex flex-col gap-4"
		class:opacity-60={!kodeposReady}
		use:enhance={() => {
			loading = true;
			return async ({ update }) => {
				loading = false;
				await update();
			};
		}}
	>
		{@render groupHeading('Identitas Toko')}
		{@render formField('warung_nama', 'Nama Warung / Toko', true, fieldNama)}
		{@render formField('deskripsi', 'Deskripsi', false, fieldDeskripsi)}
		{@render formField('kategori', 'Kategori', true, fieldKategori)}

		{@render groupHeading('Alamat & Lokasi')}
		{@render formField('alamat', 'Alamat Jalan / Detail', true, fieldAlamat)}

		<div class="form-control">
			<div class="label">
				<span class="label-text font-semibold">Wilayah & Kode Pos</span>
				{#if wilayahTerpilih}
					<button
						type="button"
						class="label-text-alt link link-hover"
						onclick={clearWilayah}
						disabled={!kodeposReady}
					>
						Cari ulang
					</button>
				{/if}
			</div>
			<p class="mb-2 text-sm text-base-content/50">Cari kelurahan, lalu data otomatis terisi & terkunci</p>

			{#if !wilayahTerpilih}
				<div class="form-control">
					<label class="label" for="cari_kelurahan">
						<span class="label-text font-semibold">Cari Kelurahan</span>
						<span class="label-text-alt text-error">*</span>
					</label>
					<div class="relative w-full">
						<input
							id="cari_kelurahan"
							type="search"
							class="input input-bordered w-full rounded-xl pr-10"
							placeholder="Ketik nama kelurahan (min. 2 huruf)..."
							value={searchQuery}
							oninput={handleSearchInput}
							autocomplete="off"
							disabled={!kodeposReady}
						/>
						{#if searchLoading}
							<span class="loading loading-spinner loading-xs absolute right-3 top-3"></span>
						{/if}
					</div>
					{#if searchError}
						<p class="mt-1 text-sm text-error">{searchError}</p>
					{/if}

					{#if showResults && searchResults.length > 0}
						<ul class="mt-2 divide-y divide-base-200 overflow-hidden rounded-xl border border-base-300">
							{#each searchResults as item (item.id)}
								<li>
									<button
										type="button"
										class="w-full px-4 py-3 text-left transition-colors hover:bg-base-200"
										onclick={() => applyWilayah(item)}
									>
										<p class="text-sm font-semibold">{formatWilayahLabel(item.kelurahan)}</p>
										<p class="text-sm text-base-content/50">
											{formatWilayahLabel(item.kecamatan)} · {formatWilayahLabel(item.kota)} ·
											{formatWilayahLabel(item.provinsi)}
										</p>
										<p class="text-sm text-base-content/50">Kode Pos {item.kode_pos}</p>
									</button>
								</li>
							{/each}
						</ul>
					{/if}
				</div>
			{/if}

			<input type="hidden" name="kodepos_id" value={kodepos_id} />
			<input type="hidden" name="provinsi" value={provinsi} />
			<input type="hidden" name="kota" value={kota} />
			<input type="hidden" name="kecamatan" value={kecamatan} />

			{#each wilayahFields as field (field.id)}
				<div class="form-control">
					<label class="label" for={field.id}>
						<span class="label-text font-semibold">{field.label}</span>
					</label>
					<input
						id={field.id}
						type="text"
						readonly
						tabindex="-1"
						class="input input-bordered w-full rounded-xl bg-base-200/70 {field.value
							? 'text-base-content'
							: 'text-base-content/35'} {field.mono ? 'font-mono' : ''}"
						value={displayWilayahValue(field.label, field.value) || 'Belum dipilih'}
					/>
				</div>
			{/each}

			{#if wilayahTerpilih}
				<p class="text-sm text-base-content/50">Wilayah terkunci — gunakan "Cari ulang" untuk mengganti.</p>
			{/if}
		</div>

		<p class="text-sm text-base-content/50">
			Buka Google Maps → klik lokasi → salin latitude & longitude
		</p>
		{@render formField('latitude', 'Latitude', true, fieldLatitude)}
		{@render formField('longitude', 'Longitude', true, fieldLongitude)}
		{#if mapsUrl}
			<a
				href={mapsUrl}
				target="_blank"
				rel="noopener noreferrer"
				class="text-sm font-semibold text-primary hover:underline"
			>
				Lihat di Google Maps
			</a>
		{/if}

		{@render groupHeading('Kontak & Operasional')}
		{@render formField('telepon', 'Telepon', false, fieldTelepon)}
		{@render formField('whatsapp', 'WhatsApp', false, fieldWhatsapp)}
		{@render formField('jam_buka', 'Jam Buka', false, fieldJamBuka)}
		{@render formField('jam_tutup', 'Jam Tutup', false, fieldJamTutup)}
		{@render formField('hari_buka_kode', 'Hari Buka', true, fieldHariBuka)}
		{@render formField('foto_url', 'URL Foto Toko', false, fieldFotoUrl)}

		{@render groupHeading('Mode Inventori')}
		<input type="hidden" name="mode_inventori" value={mode_inventori} />

		<div class="form-control gap-3">
			<button
				type="button"
				class="rounded-xl border p-3 text-left transition-colors {mode_inventori === 'tanpa_stok'
					? 'border-primary bg-primary/5'
					: 'border-base-300'}"
				onclick={() => (mode_inventori = 'tanpa_stok')}
			>
				<p class="text-sm font-semibold">Tanpa Stok</p>
				<p class="text-sm text-base-content/50">Catat penjualan manual seperti biasa. Menu stok disembunyikan.</p>
			</button>

			{#if canInventoriStok}
				<button
					type="button"
					class="rounded-xl border p-3 text-left transition-colors {mode_inventori === 'dengan_stok'
						? 'border-primary bg-primary/5'
						: 'border-base-300'}"
					onclick={() => (mode_inventori = 'dengan_stok')}
				>
					<p class="text-sm font-semibold">Dengan Stok</p>
					<p class="text-sm text-base-content/50">
						Kelola inventori barang, penjualan dari produk stok, dan stok opname.
					</p>
				</button>
			{:else}
				<div class="rounded-xl border border-dashed border-base-300 p-3">
					<p class="text-sm font-semibold text-base-content/50">Dengan Stok</p>
					<p class="text-sm text-base-content/50">
						Tersedia di paket Standar ke atas.
						<a href="/langganan" class="link link-primary">Upgrade paket →</a>
					</p>
				</div>
			{/if}
		</div>

		{@render groupHeading('Visibilitas')}

		<label class="flex cursor-pointer items-center justify-between rounded-xl border border-base-300 px-4 py-3">
			<div>
				<p class="text-sm font-semibold">Warung Aktif</p>
				<p class="text-sm text-base-content/50">Toko sedang beroperasi</p>
			</div>
			<input type="checkbox" name="is_aktif" value="1" class="toggle toggle-success" bind:checked={is_aktif} />
		</label>

		{#if canWarungPublik}
			<label class="flex cursor-pointer items-center justify-between rounded-xl border border-base-300 px-4 py-3">
				<div>
					<p class="text-sm font-semibold">Tampil di CentraWarung</p>
					<p class="text-sm text-base-content/50">Bisa ditemukan pengguna saat cari jajanan</p>
				</div>
				<input type="checkbox" name="is_publik" value="1" class="toggle toggle-primary" bind:checked={is_publik} />
			</label>
		{:else}
			<div class="rounded-xl border border-dashed border-base-300 px-4 py-3">
				<p class="text-sm font-semibold text-base-content/50">Tampil di CentraWarung</p>
				<p class="text-sm text-base-content/50">
					Tersedia di paket Premium ke atas.
					<a href="/langganan" class="link link-primary">Upgrade paket →</a>
				</p>
			</div>
		{/if}

		<button
			type="submit"
			class="btn btn-outline btn-success gap-1.5 rounded-xl"
			disabled={loading || !kodeposReady || !wilayahTerpilih}
		>
			<OutlineIcon name="store" size="xs" />
			{loading ? 'Menyimpan...' : 'Simpan Data Warung'}
		</button>
	</form>
</section>
