<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 type { JenisCatatan } from '$lib/types/transaksi';
	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 jenis = $state<JenisCatatan>((form?.values?.jenis as JenisCatatan) ?? 'pengeluaran');
	let kategori = $state(form?.values?.kategori ?? 'Bahan Baku');
	let deskripsi = $state(form?.values?.deskripsi ?? '');
	let jumlahRaw = $state(form?.values?.jumlah ?? '');
	let tanggal = $state(form?.values?.tanggal ?? data.tanggalDefault);

	const jumlah = $derived(parseRupiahInput(jumlahRaw));
	const kategoriList = $derived(jenis === 'pengeluaran' ? data.kategoriPengeluaran : data.kategoriPendapatan);

	function setJenis(value: JenisCatatan) {
		jenis = value;
		kategori = value === 'pengeluaran' ? 'Bahan Baku' : 'Pendapatan Lain';
	}

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

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

<svelte:head>
	<title>Tambah Catatan — 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-blue-600 to-indigo-600 px-4 py-4 pt-[max(1rem,env(safe-area-inset-top))] text-white">
		<a href="/transaksi/catatan" class="btn-icon-back">
			<OutlineIcon name="arrow-left" size="sm" />
		</a>
		<div>
			<h1 class="text-lg font-bold">Tambah Catatan</h1>
			<p class="text-xs text-white/70">Biaya atau pendapatan lainnya</p>
		</div>
	</header>

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

		<form id="catatan-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">
				<div class="grid grid-cols-2 gap-2">
					<button type="button" class="btn rounded-xl {jenis === 'pengeluaran' ? 'border-0 bg-rose-600 text-white' : 'btn-outline'}" onclick={() => setJenis('pengeluaran')}>📤 Pengeluaran</button>
					<button type="button" class="btn rounded-xl {jenis === 'pendapatan' ? 'border-0 bg-emerald-600 text-white' : 'btn-outline'}" onclick={() => setJenis('pendapatan')}>💵 Pemasukan</button>
				</div>
				<input type="hidden" name="jenis" value={jenis} />

				<div class="flex flex-wrap gap-2">
					{#each kategoriList as kat}
						<button type="button" class="btn btn-sm rounded-full {kategori === kat.value ? 'border-0 bg-blue-600 text-white' : 'btn-outline'}" onclick={() => (kategori = kat.value)}>
							{kat.icon} {kat.value}
						</button>
					{/each}
				</div>
				<input type="hidden" name="kategori" value={kategori} />

				<div class="form-control">
					<label class="label" for="deskripsi"><span class="label-text font-semibold">Deskripsi</span></label>
					<input id="deskripsi" name="deskripsi" type="text" class="input input-bordered" placeholder="Contoh: Beli gas elpiji 12kg" bind:value={deskripsi} required maxlength="255" />
				</div>

				<div class="form-control">
					<label class="label" for="jumlah"><span class="label-text font-semibold">Jumlah (Rp)</span></label>
					<label class="input input-bordered flex items-center gap-2">
						<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-2 flex flex-wrap gap-2">
						{#each QUICK_AMOUNTS as amount}
							<button type="button" class="btn btn-xs btn-outline rounded-full" onclick={() => addQuickAmount(amount)}>+{(amount / 1000)}rb</button>
						{/each}
					</div>
					{#if jumlah > 0}
						<p class="mt-2 text-center text-lg font-bold {jenis === 'pendapatan' ? 'text-emerald-600' : 'text-rose-600'}">{formatRupiah(jumlah)}</p>
					{/if}
				</div>

				<div class="form-control">
					<label class="label" for="tanggal"><span class="label-text font-semibold">Tanggal</span></label>
					<input id="tanggal" name="tanggal" type="date" class="input input-bordered" bind:value={tanggal} max={data.tanggalDefault} required />
				</div>

				<div class="hidden gap-3 lg:flex">
					<a href="/transaksi/catatan" class="btn btn-ghost flex-1">Batal</a>
					<button type="submit" class="btn flex-1 border-0 bg-blue-600 text-white" disabled={loading || jumlah <= 0 || !deskripsi.trim()}>
						{loading ? 'Menyimpan...' : '💾 Simpan Catatan'}
					</button>
				</div>
			</div>
		</form>
	</main>

	<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="catatan-form" class="btn w-full border-0 bg-blue-600 text-white" disabled={loading || jumlah <= 0 || !deskripsi.trim()}>
			{loading ? 'Menyimpan...' : `💾 Simpan — ${jumlah > 0 ? formatRupiah(jumlah) : 'Rp 0'}`}
		</button>
	</div>
</AppShell>
