<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_STOK, SATUAN_BARANG } from '$lib/constants/kategori-barang';
	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();

	let loading = $state(false);
	let nama = $state(form?.values?.nama ?? '');
	let kategori = $state(form?.values?.kategori ?? 'Makanan');
	let satuan = $state(form?.values?.satuan ?? 'pcs');
	let hargaBeliRaw = $state(form?.values?.harga_beli ?? '');
	let hargaJualRaw = $state(form?.values?.harga_jual ?? '');
	let stok = $state(form?.values?.stok ?? '0');
	let stokMinimum = $state(form?.values?.stok_minimum ?? '5');
	let deskripsi = $state(form?.values?.deskripsi ?? '');

	const hargaBeli = $derived(parseRupiahInput(hargaBeliRaw));
	const hargaJual = $derived(parseRupiahInput(hargaJualRaw));
	const stokNum = $derived(Number(stok));

	function handleRupiahInput(event: Event, field: 'beli' | 'jual') {
		const parsed = parseRupiahInput((event.target as HTMLInputElement).value);
		const formatted = parsed ? formatRupiahInput(parsed) : '';
		if (field === 'beli') hargaBeliRaw = formatted;
		else hargaJualRaw = formatted;
	}

	function addQuickStok(amount: number) {
		const current = Number(stok) || 0;
		stok = String(current + amount);
	}
</script>

<svelte:head>
	<title>Tambah Barang — 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-indigo-600 to-violet-600 px-4 py-4 pt-[max(1rem,env(safe-area-inset-top))] text-white lg:px-8"
	>
		<a href="/stok" class="btn-icon-back lg:hidden">
			<OutlineIcon name="arrow-left" size="sm" />
		</a>
		<div>
			<h1 class="text-lg font-bold lg:text-2xl">Tambah Barang</h1>
			<p class="text-xs text-white/70 lg:text-sm">Daftarkan barang baru ke inventori</p>
		</div>
	</header>

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

		<form
			id="barang-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 flex flex-col gap-5 p-5 lg:p-8">
				<div class="form-control w-full gap-1.5">
					<label class="label py-0" for="nama">
						<span class="label-text font-semibold">Nama Barang</span>
						<span class="label-text-alt text-error">*</span>
					</label>
					<input
						id="nama"
						name="nama"
						type="text"
						class="input input-bordered h-11 w-full rounded-xl"
						placeholder="Contoh: Beras Premium 5kg"
						bind:value={nama}
						required
						maxlength="150"
					/>
				</div>

				<div class="form-control w-full gap-1.5">
					<label class="label py-0">
						<span class="label-text font-semibold">Kategori</span>
						<span class="label-text-alt text-error">*</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-violet-600 text-white'
									: 'btn-outline'}"
								onclick={() => (kategori = kat.value)}
							>
								{kat.icon} {kat.value}
							</button>
						{/each}
					</div>
					<input type="hidden" name="kategori" value={kategori} />
				</div>

				<div class="form-control w-full gap-1.5">
					<label class="label py-0" for="satuan">
						<span class="label-text font-semibold">Satuan</span>
					</label>
					<select
						id="satuan"
						name="satuan"
						class="select select-bordered h-11 w-full max-w-none rounded-xl"
						bind:value={satuan}
					>
						{#each SATUAN_BARANG as s}
							<option value={s.value}>{s.label}</option>
						{/each}
					</select>
				</div>

				<div class="form-control w-full gap-1.5">
					<label class="label py-0" for="harga_beli">
						<span class="label-text font-semibold">Harga Beli (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="harga_beli"
							name="harga_beli"
							type="text"
							inputmode="numeric"
							class="grow"
							placeholder="Opsional"
							value={hargaBeliRaw}
							oninput={(e) => handleRupiahInput(e, 'beli')}
						/>
					</label>
				</div>

				<div class="form-control w-full gap-1.5">
					<label class="label py-0" for="harga_jual">
						<span class="label-text font-semibold">Harga Jual (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="harga_jual"
							name="harga_jual"
							type="text"
							inputmode="numeric"
							class="grow"
							placeholder="Opsional"
							value={hargaJualRaw}
							oninput={(e) => handleRupiahInput(e, 'jual')}
						/>
					</label>
					{#if hargaJual > 0 && hargaBeli > 0 && hargaJual > hargaBeli}
						<p class="text-xs text-emerald-600">
							Margin: {formatRupiah(hargaJual - hargaBeli)} per {satuan}
						</p>
					{/if}
				</div>

				<div class="form-control w-full gap-1.5">
					<label class="label py-0" for="stok">
						<span class="label-text font-semibold">Stok Awal</span>
					</label>
					<input
						id="stok"
						name="stok"
						type="number"
						min="0"
						class="input input-bordered h-11 w-full rounded-xl"
						bind:value={stok}
						required
					/>
					<div class="mt-2 flex flex-wrap gap-2">
						{#each QUICK_STOK as amount}
							<button
								type="button"
								class="btn btn-xs btn-outline rounded-full"
								onclick={() => addQuickStok(amount)}
							>
								+{amount}
							</button>
						{/each}
					</div>
				</div>

				<div class="form-control w-full gap-1.5">
					<label class="label py-0" for="stok_minimum">
						<span class="label-text font-semibold">Stok Minimum (peringatan)</span>
					</label>
					<input
						id="stok_minimum"
						name="stok_minimum"
						type="number"
						min="0"
						class="input input-bordered h-11 w-full rounded-xl"
						bind:value={stokMinimum}
						required
					/>
					<p class="text-xs text-base-content/50">Akan muncul peringatan jika stok di bawah angka ini</p>
				</div>

				<div class="form-control w-full gap-1.5">
					<label class="label py-0" for="deskripsi">
						<span class="label-text font-semibold">Deskripsi / Catatan</span>
					</label>
					<textarea
						id="deskripsi"
						name="deskripsi"
						class="textarea textarea-bordered min-h-20 w-full rounded-xl"
						placeholder="Contoh: Supplier langganan, expired 30 hari..."
						bind:value={deskripsi}
						maxlength="255"
					></textarea>
				</div>

				<div class="hidden gap-3 pt-2 lg:flex">
					<a href="/stok" class="btn btn-ghost flex-1 rounded-xl">Batal</a>
					<button
						type="submit"
						class="btn flex-1 rounded-xl border-0 bg-gradient-to-r from-indigo-600 to-violet-600 text-white"
						disabled={loading || !nama.trim()}
					>
						{#if loading}
							<span class="loading loading-spinner loading-sm"></span> Menyimpan...
						{:else}
							💾 Simpan Barang
						{/if}
					</button>
				</div>
			</div>
		</form>
	</main>

	<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="barang-form"
			class="btn w-full rounded-xl border-0 bg-gradient-to-r from-indigo-600 to-violet-600 text-white"
			disabled={loading || !nama.trim()}
		>
			{loading ? 'Menyimpan...' : `💾 Simpan Barang${stokNum > 0 ? ` — Stok ${stokNum}` : ''}`}
		</button>
	</div>
</AppShell>
