<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 type { ActionData, PageData } from './$types';

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

	let loading = $state(false);
	let tanggal = $state(data.tanggalDefault);
	let keterangan = $state('');
	let stokFisik = $state<Record<number, number>>(
		Object.fromEntries(data.barangList.map((b) => [b.id, b.stok]))
	);

	const totalSelisih = $derived(
		data.barangList.filter((b) => (stokFisik[b.id] ?? b.stok) !== b.stok).length
	);
</script>

<svelte:head>
	<title>Opname Baru — 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-violet-600 to-purple-600 px-4 py-4 pt-[max(1rem,env(safe-area-inset-top))] text-white">
		<a href="/stok/opname" class="btn-icon-back">
			<OutlineIcon name="arrow-left" size="sm" />
		</a>
		<div>
			<h1 class="text-lg font-bold">Opname Baru</h1>
			<p class="text-xs text-white/70">Hitung stok fisik di warung</p>
		</div>
	</header>

	<main class="page-content-narrow pb-32 lg:pb-8">
		<FlashToast message={form?.error} type="error" />

		{#if data.barangList.length === 0}
			<div class="card bg-base-100 shadow-md">
				<div class="card-body items-center py-12 text-center">
					<p class="font-bold">Belum ada barang aktif</p>
					<a href="/stok/tambah" class="btn mt-4 border-0 bg-violet-600 text-white">➕ Tambah Barang</a>
				</div>
			</div>
		{:else}
			<form
				id="opname-form"
				method="POST"
				class="space-y-4"
				use:enhance={() => {
					loading = true;
					return async ({ update }) => {
						loading = false;
						await update();
					};
				}}
			>
				<div class="card bg-base-100 shadow-md">
					<div class="card-body gap-4 p-4">
						<div class="form-control">
							<label class="label py-0" for="tanggal"><span class="label-text font-semibold">Tanggal Opname</span></label>
							<input id="tanggal" name="tanggal" type="date" class="input input-bordered w-full" bind:value={tanggal} max={data.tanggalDefault} required />
						</div>
						<div class="form-control">
							<label class="label py-0" for="keterangan"><span class="label-text font-semibold">Keterangan</span></label>
							<input id="keterangan" name="keterangan" type="text" class="input input-bordered w-full" placeholder="Contoh: Opname akhir bulan" bind:value={keterangan} />
						</div>
					</div>
				</div>

				<div class="rounded-xl bg-base-100 p-3 text-sm text-base-content/60">
					Masukkan <strong>stok fisik</strong> hasil hitung. Selisih: <strong>{totalSelisih}</strong> barang
				</div>

				<div class="flex flex-col gap-3">
					{#each data.barangList as barang (barang.id)}
						{@const fisik = stokFisik[barang.id] ?? barang.stok}
						{@const selisih = fisik - barang.stok}
						<div class="card bg-base-100 shadow-sm">
							<div class="card-body gap-3 p-4">
								<div class="flex items-start justify-between gap-3">
									<div>
										<p class="font-semibold">{barang.nama}</p>
										<p class="text-xs text-base-content/50">{barang.kategori} · {barang.satuan}</p>
									</div>
									<span class="badge badge-sm {selisih === 0 ? 'badge-ghost' : selisih > 0 ? 'badge-success' : 'badge-error'}">
										{selisih === 0 ? 'OK' : selisih > 0 ? `+${selisih}` : selisih}
									</span>
								</div>
								<div class="grid grid-cols-2 gap-3">
									<div>
										<p class="text-xs text-base-content/50">Stok Sistem</p>
										<p class="text-lg font-bold">{barang.stok}</p>
									</div>
									<div class="form-control">
										<label class="label py-0" for="stok_{barang.id}">
											<span class="label-text text-xs font-semibold">Stok Fisik</span>
										</label>
										<input
											id="stok_{barang.id}"
											name="stok_fisik_{barang.id}"
											type="number"
											min="0"
											class="input input-bordered input-sm w-full"
											value={fisik}
											oninput={(e) => {
												const value = Number((e.target as HTMLInputElement).value);
												stokFisik = { ...stokFisik, [barang.id]: value };
											}}
											required
										/>
									</div>
								</div>
							</div>
						</div>
					{/each}
				</div>

				<div class="hidden lg:block">
					<button type="submit" class="btn w-full border-0 bg-violet-600 text-white" disabled={loading}>
						{loading ? 'Menyimpan...' : `💾 Simpan Opname (${totalSelisih} selisih)`}
					</button>
				</div>
			</form>
		{/if}
	</main>

	{#if data.barangList.length > 0}
		<div class="fixed bottom-0 left-0 right-0 z-40 border-t bg-base-100/95 p-4 pb-[max(1rem,env(safe-area-inset-bottom))] backdrop-blur-lg lg:hidden">
			<button type="submit" form="opname-form" class="btn w-full border-0 bg-violet-600 text-white" disabled={loading}>
				{loading ? 'Menyimpan...' : `💾 Simpan Opname`}
			</button>
		</div>
	{/if}
</AppShell>
