<script lang="ts">
	import { enhance } from '$app/forms';
	import { goto } from '$app/navigation';
	import AppShell from '$lib/components/layout/AppShell.svelte';
	import FlashToast from '$lib/components/ui/FlashToast.svelte';
	import IconRing from '$lib/components/ui/IconRing.svelte';
	import OutlineIcon from '$lib/components/ui/OutlineIcon.svelte';
	import type { FilterHutangPiutang } from '$lib/types/hutang-piutang';
	import { confirmBeforeSubmit } from '$lib/utils/confirm';
	import { formatRupiah } from '$lib/utils/format';
	import type { PageData } from './$types';

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

	const filters: { value: FilterHutangPiutang; label: string }[] = [
		{ value: 'semua', label: 'Semua' },
		{ value: 'belum_lunas', label: 'Belum Lunas' },
		{ value: 'hutang', label: 'Hutang' },
		{ value: 'piutang', label: 'Piutang' }
	];

	let actionId = $state<number | null>(null);

	function setFilter(filter: FilterHutangPiutang) {
		goto(`/transaksi/hutang-piutang?filter=${filter}`, { replaceState: true, keepFocus: true });
	}
</script>

<svelte:head>
	<title>Hutang & Piutang — Catatan Warung</title>
</svelte:head>

<FlashToast message={data.success ? 'Data berhasil disimpan!' : undefined} />

<AppShell memberName={data.member.nama} memberEmail={data.member.email}>
	<header class="mobile-subpage-header bg-gradient-to-r from-amber-500 to-orange-600">
		<div class="flex items-center gap-3">
			<a href="/transaksi" class="btn-icon-back lg:hidden">
				<OutlineIcon name="arrow-left" size="sm" />
			</a>
			<div class="flex-1">
				<h1 class="text-lg font-bold lg:text-2xl">Hutang & Piutang</h1>
				<p class="text-xs text-white/70 lg:text-sm">Catat utang dan piutang warung</p>
			</div>
			<a href="/transaksi/hutang-piutang/tambah" class="btn-outline-on-dark hidden gap-1.5 lg:inline-flex">
				<OutlineIcon name="plus" size="xs" />
				Tambah
			</a>
		</div>
		<a href="/transaksi/hutang-piutang/tambah" class="btn-outline-on-dark gap-1.5 lg:hidden">
			<OutlineIcon name="plus" size="xs" />
			Tambah Data
		</a>
	</header>

	<main class="page-content">
		<div class="grid grid-cols-2 gap-3 lg:grid-cols-3">
			<div class="surface-red rounded-2xl p-4">
				<p class="text-xs text-white/75">Total Hutang</p>
				<p class="text-lg font-bold">{formatRupiah(data.summary.totalHutang)}</p>
			</div>
			<div class="surface-green rounded-2xl p-4">
				<p class="text-xs text-white/75">Total Piutang</p>
				<p class="text-lg font-bold">{formatRupiah(data.summary.totalPiutang)}</p>
			</div>
			<div class="col-span-2 rounded-2xl bg-base-100 p-4 shadow-sm lg:col-span-1">
				<p class="text-xs text-base-content/50">Belum Lunas</p>
				<p class="text-lg font-bold">{data.summary.jumlahBelumLunas} catatan</p>
			</div>
		</div>

		<div class="flex gap-2 overflow-x-auto pb-1">
			{#each filters as f}
				<button type="button" class="btn btn-sm shrink-0 rounded-full {data.filter === f.value ? 'border-0 bg-amber-500 text-white' : 'btn-ghost bg-base-100'}" onclick={() => setFilter(f.value)}>{f.label}</button>
			{/each}
		</div>

		{#if data.items.length === 0}
			<div class="card bg-base-100 shadow-md">
				<div class="card-body items-center py-12 text-center">
					<OutlineIcon name="hutang" size="xl" class="text-base-content/30" />
					<p class="mt-3 font-bold">Belum ada hutang/piutang</p>
					<a href="/transaksi/hutang-piutang/tambah" class="btn mt-4 border-0 bg-amber-500 text-white">➕ Tambah Data</a>
				</div>
			</div>
		{:else}
			<div class="grid gap-3 lg:grid-cols-2">
				{#each data.items as item (item.id)}
					<div class="card bg-base-100 shadow-md {item.status === 'lunas' ? 'opacity-60' : ''}">
						<div class="card-body gap-3 p-4">
							<div class="flex items-start gap-2">
								<IconRing
									tone={item.jenis === 'hutang' ? 'rose' : 'emerald'}
									size="sm"
									shape="circle"
									class="shrink-0"
								>
									<OutlineIcon
										name={item.jenis === 'hutang' ? 'arrow-up-right' : 'arrow-down-left'}
										size="sm"
									/>
								</IconRing>
								<div class="min-w-0 flex-1">
									<div class="flex items-start justify-between gap-2">
										<p class="min-w-0 break-words font-bold leading-snug">{item.nama}</p>
										<span
											class="badge badge-sm shrink-0 whitespace-nowrap {item.status === 'lunas'
												? 'badge-success'
												: 'badge-warning'}"
										>
											{item.status === 'lunas' ? 'Lunas' : 'Belum Lunas'}
										</span>
									</div>
									<p class="mt-0.5 line-clamp-2 text-xs text-base-content/50">
										{item.deskripsi ||
											(item.jenis === 'hutang'
												? 'Hutang ke pihak lain'
												: 'Piutang dari pelanggan')}
									</p>
								</div>
							</div>
							<div class="flex items-center justify-between">
								<div>
									<p class="text-xs text-base-content/50">Sisa</p>
									<p class="text-lg font-bold {item.jenis === 'hutang' ? 'text-rose-600' : 'text-emerald-600'}">{formatRupiah(item.sisa)}</p>
									<p class="text-[10px] text-base-content/40">dari {formatRupiah(item.jumlah)}</p>
								</div>
								{#if item.jatuh_tempo}
									<div class="text-right text-xs text-base-content/50">Jatuh tempo<br /><strong>{item.jatuh_tempo}</strong></div>
								{/if}
							</div>
							{#if item.status === 'belum_lunas'}
								<div class="flex gap-2">
									<form method="POST" action="?/lunasi" class="flex-1" use:enhance={() => { actionId = item.id; return async ({ update }) => { actionId = null; await update(); }; }}>
										<input type="hidden" name="id" value={item.id} />
										<button type="submit" class="btn btn-success btn-sm w-full" disabled={actionId === item.id}>✓ Lunasi</button>
									</form>
									<form method="POST" action="?/hapus" use:enhance={() => { actionId = item.id; return async ({ update }) => { actionId = null; await update(); }; }}>
										<input type="hidden" name="id" value={item.id} />
										<button
											type="submit"
											class="btn btn-ghost btn-sm text-rose-500"
											disabled={actionId === item.id}
											onclick={(e) =>
												confirmBeforeSubmit(e, {
													title: 'Hapus Data',
													message: 'Data hutang/piutang ini akan dihapus permanen. Lanjutkan?',
													confirmText: 'Hapus',
													tone: 'danger'
												})}
										>
											Hapus
										</button>
									</form>
								</div>
							{/if}
						</div>
					</div>
				{/each}
			</div>
		{/if}
	</main>
</AppShell>
