<script lang="ts">
	import { enhance } from '$app/forms';
	import AppShell from '$lib/components/layout/AppShell.svelte';
	import FlashToast from '$lib/components/ui/FlashToast.svelte';
	import OutlineIcon from '$lib/components/ui/OutlineIcon.svelte';
	import { QUICK_AMOUNTS } from '$lib/constants/kategori';
	import { formatRupiah } from '$lib/utils/format';
	import { formatRupiahInput, parseRupiahInput } from '$lib/utils/parse';
	import type { ActionData, PageData } from './$types';

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

	type JenisPenjualan = 'manual' | 'stok';

	let loading = $state(false);
	let jenisPenjualan = $state<JenisPenjualan>(
		(form?.values?.jenis_penjualan as JenisPenjualan) ?? 'manual'
	);
	let kategori = $state(String(form?.values?.kategori ?? 'Makanan'));
	let deskripsi = $state(String(form?.values?.deskripsi ?? ''));
	let jumlahRaw = $state(String(form?.values?.jumlah ?? ''));
	let tanggal = $state(String(form?.values?.tanggal ?? data.tanggalDefault));
	let barangId = $state(Number(form?.values?.barang_id ?? 0));
	let qty = $state(Number(form?.values?.qty ?? 1));
	let searchQuery = $state('');
	let showSearchResults = $state(false);

	const jumlah = $derived(parseRupiahInput(jumlahRaw));
	const selectedBarang = $derived(data.barangList.find((b) => b.id === barangId) ?? null);

	const filteredBarang = $derived.by(() => {
		const q = searchQuery.trim().toLowerCase();
		if (!q) return data.barangList.slice(0, 8);
		return data.barangList.filter(
			(b) =>
				b.nama.toLowerCase().includes(q) ||
				b.kategori.toLowerCase().includes(q) ||
				b.satuan.toLowerCase().includes(q)
		);
	});

	const canSubmitManual = $derived(jumlah > 0 && deskripsi.trim().length > 0);
	const canSubmitStok = $derived(
		Boolean(barangId) && qty > 0 && jumlah > 0 && (selectedBarang ? qty <= selectedBarang.stok : false)
	);
	const canSubmit = $derived(jenisPenjualan === 'stok' ? canSubmitStok : canSubmitManual);

	function setJenis(jenis: JenisPenjualan) {
		jenisPenjualan = jenis;
		if (jenis === 'manual') {
			barangId = 0;
			searchQuery = '';
			showSearchResults = false;
		}
	}

	function selectKategori(value: string) {
		kategori = value;
	}

	function selectBarang(id: number) {
		barangId = id;
		const barang = data.barangList.find((b) => b.id === id);
		if (barang) {
			searchQuery = barang.nama;
			if (barang.harga_jual) {
				jumlahRaw = formatRupiahInput(barang.harga_jual * qty);
			}
		}
		showSearchResults = false;
	}

	function clearBarang() {
		barangId = 0;
		searchQuery = '';
		qty = 1;
		jumlahRaw = '';
		showSearchResults = true;
	}

	function updateQty(value: number) {
		qty = Math.max(1, value);
		if (selectedBarang?.harga_jual) {
			jumlahRaw = formatRupiahInput(selectedBarang.harga_jual * qty);
		}
	}

	function handleSearchInput(event: Event) {
		const target = event.currentTarget as HTMLInputElement;
		searchQuery = target.value;
		showSearchResults = true;
		if (!searchQuery.trim()) barangId = 0;
	}

	function handleJumlahInput(event: Event) {
		const parsed = parseRupiahInput((event.target as HTMLInputElement).value);
		jumlahRaw = parsed ? formatRupiahInput(parsed) : '';
	}

	function addQuickAmount(amount: number) {
		const current = parseRupiahInput(jumlahRaw);
		jumlahRaw = formatRupiahInput(current + amount);
	}
</script>

<svelte:head>
	<title>Tambah Penjualan — Catatan Warung</title>
</svelte:head>

<AppShell memberName={data.member.nama} memberEmail={data.member.email} hideBottomNav={true}>
	<header
		class="flex items-center gap-3 bg-gradient-to-r from-emerald-600 to-teal-600 px-4 py-4 pt-[max(1rem,env(safe-area-inset-top))] text-white lg:hidden"
	>
		<a href="/transaksi/penjualan" class="btn-icon-back" aria-label="Kembali">
			<OutlineIcon name="arrow-left" size="sm" />
		</a>
		<div>
			<h1 class="text-lg font-bold">Tambah Penjualan</h1>
			<p class="text-xs text-white/70">
				{data.pakaiStok ? 'Pilih jenis penjualan' : 'Catat penjualan manual'}
			</p>
		</div>
	</header>

	<header class="hidden items-center gap-4 border-b border-base-300 bg-base-100 px-8 py-5 lg:flex">
		<a href="/transaksi/penjualan" class="btn btn-ghost btn-sm">← Kembali</a>
		<div>
			<h1 class="text-2xl font-bold">Tambah Penjualan</h1>
			<p class="text-sm text-base-content/50">
				{data.pakaiStok
					? 'Manual atau dari produk stok — stok otomatis berkurang saat jual produk'
					: 'Isi detail penjualan warung Anda'}
			</p>
		</div>
	</header>

	<main class="page-content-form">
		<FlashToast message={form?.error} type="error" />

		<form
			id="penjualan-form"
			method="POST"
			class="card bg-base-100 shadow-xl"
			use:enhance={() => {
				loading = true;
				return async ({ update }) => {
					loading = false;
					await update();
				};
			}}
		>
			<div class="card-body gap-5 p-5 lg:p-8">
				<input type="hidden" name="jenis_penjualan" value={jenisPenjualan} />

				{#if data.pakaiStok}
					<div class="grid grid-cols-2 gap-2 rounded-xl bg-base-200/60 p-1">
						<button
							type="button"
							class="rounded-lg px-3 py-2.5 text-sm font-semibold transition-colors {jenisPenjualan === 'manual'
								? 'bg-base-100 text-emerald-700 shadow-sm'
								: 'text-base-content/50'}"
							onclick={() => setJenis('manual')}
						>
							📝 Tanpa Stok
						</button>
						<button
							type="button"
							class="rounded-lg px-3 py-2.5 text-sm font-semibold transition-colors {jenisPenjualan === 'stok'
								? 'bg-base-100 text-violet-700 shadow-sm'
								: 'text-base-content/50'}"
							onclick={() => setJenis('stok')}
						>
							📦 Dari Stok
						</button>
					</div>
					<p class="text-xs text-base-content/50">
						{jenisPenjualan === 'manual'
							? 'Catat penjualan bebas tanpa mengurangi stok.'
							: 'Pilih produk — stok berkurang otomatis setelah disimpan.'}
					</p>
				{/if}

				{#if jenisPenjualan === 'stok' && data.pakaiStok}
					{#if data.barangList.length === 0}
						<div class="rounded-xl bg-amber-50 p-4 text-center">
							<p class="font-semibold text-amber-800">Belum ada produk di stok</p>
							<a href="/stok/tambah" class="btn btn-sm mt-3 border-0 bg-amber-500 text-white">➕ Tambah Barang</a>
						</div>
					{:else}
						{#if selectedBarang}
							<div class="surface-violet rounded-xl border-2 border-violet-400 p-4">
								<div class="flex items-start justify-between gap-3">
									<div class="min-w-0 flex-1">
										<p class="font-bold">{selectedBarang.nama}</p>
										<p class="mt-0.5 text-xs text-white/75">
											{selectedBarang.kategori} · Stok {selectedBarang.stok} {selectedBarang.satuan}
											{#if selectedBarang.harga_jual}
												· {formatRupiah(selectedBarang.harga_jual)}/{selectedBarang.satuan}
											{/if}
										</p>
									</div>
									<button type="button" class="btn btn-xs shrink-0 border-white/30 bg-white/10 text-white hover:bg-white/20" onclick={clearBarang}>
										Ganti
									</button>
								</div>
							</div>
						{:else}
							<div class="form-control">
								<label class="label py-0" for="cari_produk">
									<span class="label-text font-semibold">Cari Produk</span>
								</label>
								<div class="relative">
									<input
										id="cari_produk"
										type="search"
										class="input input-bordered h-11 w-full rounded-xl pr-10"
										placeholder="Ketik nama produk..."
										value={searchQuery}
										oninput={handleSearchInput}
										onfocus={() => (showSearchResults = true)}
										autocomplete="off"
									/>
									<span class="pointer-events-none absolute right-3 top-3 text-base-content/30">🔍</span>
								</div>
								<p class="mt-1 text-xs text-base-content/40">
									{data.barangList.length} produk tersedia · ketik untuk memfilter
								</p>

								{#if showSearchResults && filteredBarang.length > 0}
									<ul
										class="mt-2 max-h-52 divide-y divide-base-200 overflow-y-auto rounded-xl border border-base-300 bg-base-100 shadow-sm"
									>
										{#each filteredBarang as barang (barang.id)}
											<li>
												<button
													type="button"
													class="w-full px-4 py-3 text-left transition-colors hover:bg-violet-50"
													onclick={() => selectBarang(barang.id)}
												>
													<p class="text-sm font-semibold">{barang.nama}</p>
													<p class="text-xs text-base-content/50">
														{barang.kategori} · {barang.stok} {barang.satuan}
														{#if barang.harga_jual} · {formatRupiah(barang.harga_jual)}{/if}
													</p>
												</button>
											</li>
										{/each}
									</ul>
								{:else if showSearchResults && searchQuery.trim()}
									<p class="mt-2 text-xs text-error">Produk tidak ditemukan.</p>
								{/if}
							</div>
						{/if}

						<input type="hidden" name="barang_id" value={barangId} />

						<div class="form-control">
							<label class="label py-0" for="qty"><span class="label-text font-semibold">Jumlah Terjual</span></label>
							<input
								id="qty"
								name="qty"
								type="number"
								min="1"
								max={selectedBarang?.stok ?? 9999}
								class="input input-bordered h-11 w-full rounded-xl"
								value={qty}
								oninput={(e) => updateQty(Number((e.target as HTMLInputElement).value))}
								required
								disabled={!barangId}
							/>
							{#if selectedBarang}
								<p class="mt-1 text-xs text-base-content/50">Maks. {selectedBarang.stok} {selectedBarang.satuan}</p>
							{/if}
						</div>

						<div class="form-control">
							<label class="label py-0" for="jumlah_stok"><span class="label-text font-semibold">Total (Rp)</span></label>
							<label class="input input-bordered flex h-11 items-center gap-2 rounded-xl">
								<span class="text-base-content/50">Rp</span>
								<input
									id="jumlah_stok"
									name="jumlah"
									type="text"
									inputmode="numeric"
									class="grow font-bold"
									value={jumlahRaw}
									oninput={handleJumlahInput}
									required
									disabled={!barangId}
								/>
							</label>
							{#if jumlah > 0}
								<div class="surface-green mt-2 rounded-xl px-4 py-3 text-center">
									<p class="text-xl font-extrabold">{formatRupiah(jumlah)}</p>
								</div>
							{/if}
						</div>
					{/if}
				{:else}
					<div class="form-control">
						<label class="label py-0"><span class="label-text font-semibold">Kategori</span></label>
						<div class="flex flex-wrap gap-2">
							{#each data.kategori as kat}
								<button
									type="button"
									class="btn btn-sm rounded-full {kategori === kat.value
										? 'border-0 bg-emerald-600 text-white'
										: 'btn-outline'}"
									onclick={() => selectKategori(kat.value)}
								>
									{kat.icon} {kat.value}
								</button>
							{/each}
						</div>
						<input type="hidden" name="kategori" value={kategori} />
					</div>

					<div class="form-control">
						<label class="label py-0" for="deskripsi"><span class="label-text font-semibold">Deskripsi Penjualan</span></label>
						<input
							id="deskripsi"
							name="deskripsi"
							type="text"
							class="input input-bordered h-11 w-full rounded-xl"
							placeholder="Contoh: Nasi goreng spesial 5 porsi"
							bind:value={deskripsi}
							required
							maxlength="255"
						/>
					</div>

					<div class="form-control">
						<label class="label py-0" for="jumlah"><span class="label-text font-semibold">Jumlah (Rp)</span></label>
						<label class="input input-bordered flex h-11 items-center gap-2 rounded-xl">
							<span class="text-base-content/50">Rp</span>
							<input
								id="jumlah"
								name="jumlah"
								type="text"
								inputmode="numeric"
								class="grow font-bold"
								value={jumlahRaw}
								oninput={handleJumlahInput}
								required
							/>
						</label>
						<div class="mt-3 flex flex-wrap gap-2">
							{#each QUICK_AMOUNTS as amount}
								<button type="button" class="btn btn-xs btn-outline rounded-full" onclick={() => addQuickAmount(amount)}>
									+{formatRupiah(amount).replace('Rp', '').trim()}
								</button>
							{/each}
						</div>
						{#if jumlah > 0}
							<div class="surface-green mt-2 rounded-xl px-4 py-3 text-center">
								<p class="text-xl font-extrabold">{formatRupiah(jumlah)}</p>
							</div>
						{/if}
					</div>
				{/if}

				{#if !data.pakaiStok || jenisPenjualan === 'manual' || data.barangList.length > 0}
					<div class="form-control">
						<label class="label py-0" for="tanggal"><span class="label-text font-semibold">Tanggal</span></label>
						<input
							id="tanggal"
							name="tanggal"
							type="date"
							class="input input-bordered h-11 w-full rounded-xl"
							bind:value={tanggal}
							max={data.tanggalDefault}
							required
						/>
					</div>

					<div class="hidden gap-3 pt-2 lg:flex">
						<a href="/transaksi/penjualan" class="btn btn-ghost flex-1">Batal</a>
						<button
							type="submit"
							class="btn flex-1 border-0 bg-gradient-to-r from-emerald-500 to-teal-600 text-white"
							disabled={loading || !canSubmit}
						>
							{loading ? 'Menyimpan...' : '💾 Simpan Penjualan'}
						</button>
					</div>
				{/if}
			</div>
		</form>
	</main>

	{#if !data.pakaiStok || jenisPenjualan === 'manual' || data.barangList.length > 0}
		<div
			class="fixed bottom-0 left-0 right-0 z-40 border-t border-base-300 bg-base-100/95 p-4 pb-[max(1rem,env(safe-area-inset-bottom))] backdrop-blur-lg lg:hidden"
		>
			<button
				type="submit"
				form="penjualan-form"
				class="btn w-full border-0 bg-gradient-to-r from-emerald-500 to-teal-600 text-white"
				disabled={loading || !canSubmit}
			>
				{loading ? 'Menyimpan...' : `💾 Simpan — ${jumlah > 0 ? formatRupiah(jumlah) : 'Rp 0'}`}
			</button>
		</div>
	{/if}
</AppShell>
