<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 { JenisHutangPiutang } from '$lib/types/hutang-piutang';
	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<JenisHutangPiutang>((form?.values?.jenis as JenisHutangPiutang) ?? 'hutang');
	let nama = $state(form?.values?.nama ?? '');
	let deskripsi = $state(form?.values?.deskripsi ?? '');
	let jumlahRaw = $state(form?.values?.jumlah ?? '');
	let tanggal = $state(form?.values?.tanggal ?? data.tanggalDefault);
	let jatuhTempo = $state(form?.values?.jatuh_tempo ?? '');

	const jumlah = $derived(parseRupiahInput(jumlahRaw));

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

<svelte:head>
	<title>Tambah Hutang/Piutang — 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-amber-500 to-orange-600 px-4 py-4 pt-[max(1rem,env(safe-area-inset-top))] text-white">
		<a href="/transaksi/hutang-piutang" class="btn-icon-back">
			<OutlineIcon name="arrow-left" size="sm" />
		</a>
		<div>
			<h1 class="text-lg font-bold">Tambah Hutang/Piutang</h1>
			<p class="text-xs text-white/70">Catat utang atau piutang baru</p>
		</div>
	</header>

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

		<form id="hp-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 === 'hutang' ? 'border-0 bg-rose-600 text-white' : 'btn-outline'}" onclick={() => (jenis = 'hutang')}>📤 Hutang</button>
					<button type="button" class="btn rounded-xl {jenis === 'piutang' ? 'border-0 bg-emerald-600 text-white' : 'btn-outline'}" onclick={() => (jenis = 'piutang')}>📥 Piutang</button>
				</div>
				<input type="hidden" name="jenis" value={jenis} />

				<div class="form-control">
					<label class="label" for="nama"><span class="label-text font-semibold">{jenis === 'hutang' ? 'Nama Pemberi Hutang' : 'Nama Debitur'}</span></label>
					<input id="nama" name="nama" type="text" class="input input-bordered" placeholder={jenis === 'hutang' ? 'Contoh: Toko Sembako Pak Budi' : 'Contoh: Ibu Siti'} bind:value={nama} required />
				</div>

				<div class="form-control">
					<label class="label" for="deskripsi"><span class="label-text font-semibold">Keterangan</span></label>
					<input id="deskripsi" name="deskripsi" type="text" class="input input-bordered" placeholder="Contoh: Beli beras bon 50kg" bind:value={deskripsi} />
				</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>
					{#if jumlah > 0}<p class="mt-2 text-center text-lg font-bold text-amber-600">{formatRupiah(jumlah)}</p>{/if}
				</div>

				<div class="grid grid-cols-2 gap-3">
					<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="form-control">
						<label class="label" for="jatuh_tempo"><span class="label-text font-semibold">Jatuh Tempo</span></label>
						<input id="jatuh_tempo" name="jatuh_tempo" type="date" class="input input-bordered" bind:value={jatuhTempo} />
					</div>
				</div>

				<div class="hidden gap-3 lg:flex">
					<a href="/transaksi/hutang-piutang" class="btn btn-ghost flex-1">Batal</a>
					<button type="submit" class="btn flex-1 border-0 bg-amber-500 text-white" disabled={loading || jumlah <= 0 || !nama.trim()}>
						{loading ? 'Menyimpan...' : '💾 Simpan'}
					</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="hp-form" class="btn w-full border-0 bg-amber-500 text-white" disabled={loading || jumlah <= 0 || !nama.trim()}>
			{loading ? 'Menyimpan...' : `💾 Simpan — ${jumlah > 0 ? formatRupiah(jumlah) : 'Rp 0'}`}
		</button>
	</div>
</AppShell>
