<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 { 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 ?? data.barang.nama);
	let kategori = $state(form?.values?.kategori ?? data.barang.kategori);
	let satuan = $state(form?.values?.satuan ?? data.barang.satuan);
	let hargaBeliRaw = $state(
		form?.values?.harga_beli ??
			(data.barang.harga_beli != null ? formatRupiahInput(data.barang.harga_beli) : '')
	);
	let hargaJualRaw = $state(
		form?.values?.harga_jual ??
			(data.barang.harga_jual != null ? formatRupiahInput(data.barang.harga_jual) : '')
	);
	let stokMinimum = $state(form?.values?.stok_minimum ?? String(data.barang.stok_minimum));
	let deskripsi = $state(form?.values?.deskripsi ?? data.barang.deskripsi);
	let isAktif = $state(form?.values?.is_aktif ?? data.barang.is_aktif);

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

	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;
	}
</script>

<svelte:head>
	<title>Edit 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">Edit Barang</h1>
			<p class="text-xs text-white/70 lg:text-sm">Perbarui data {data.barang.nama}</p>
		</div>
	</header>

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

		<div class="surface-violet mb-4 rounded-xl p-4">
			<p class="text-xs text-white/75">Stok saat ini</p>
			<p class="text-2xl font-bold">
				{data.barang.stok} {data.barang.satuan}
			</p>
			<p class="mt-1 text-xs text-white/70">
				Ubah stok melalui tombol Stok Masuk / Keluar di halaman stok
			</p>
		</div>

		<form
			id="edit-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"
						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"
							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"
							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_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
					/>
				</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"
						bind:value={deskripsi}
						maxlength="255"
					></textarea>
				</div>

				<label
					class="flex cursor-pointer items-center justify-between rounded-xl border border-base-300 bg-base-200/40 px-4 py-3.5"
				>
					<div>
						<p class="text-sm font-semibold">Barang Aktif</p>
						<p class="text-xs text-base-content/50">Nonaktifkan jika barang tidak dijual lagi</p>
					</div>
					<input type="checkbox" name="is_aktif" value="1" class="toggle toggle-success" bind:checked={isAktif} />
				</label>

				<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()}
					>
						{loading ? 'Menyimpan...' : '💾 Simpan Perubahan'}
					</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="edit-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 Perubahan'}
		</button>
	</div>
</AppShell>
