<script lang="ts">
	import { browser } from '$app/environment';
	import { goto } from '$app/navigation';
	import AppShell from '$lib/components/layout/AppShell.svelte';
	import LaporanDateFilter from '$lib/components/laporan/LaporanDateFilter.svelte';
	import LaporanExportButton from '$lib/components/laporan/LaporanExportButton.svelte';
	import LaporanMenu from '$lib/components/laporan/LaporanMenu.svelte';
	import type { FilterJenisCatatan } from '$lib/types/laporan-detail';
	import { formatLaporanTanggalLabel } from '$lib/utils/laporan-date';
	import { formatRupiah } from '$lib/utils/format';
	import type { PageData } from './$types';

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

	let exporting = $state(false);
	let jenisLoading = $state(false);

	const laporan = $derived(data.laporan);
	const periodeLabel = $derived(formatLaporanTanggalLabel(laporan.tanggalAwal, laporan.tanggalAkhir));

	const jenisOptions: { value: FilterJenisCatatan; label: string }[] = [
		{ value: 'semua', label: 'Semua' },
		{ value: 'pendapatan', label: 'Pemasukan' },
		{ value: 'pengeluaran', label: 'Pengeluaran' }
	];

	function setJenis(jenis: FilterJenisCatatan) {
		if (laporan.jenis === jenis || jenisLoading) return;
		jenisLoading = true;
		const params = new URLSearchParams({
			dari: laporan.tanggalAwal,
			sampai: laporan.tanggalAkhir,
			jenis
		});
		goto(`/laporan/catatan?${params.toString()}`, {
			replaceState: true,
			keepFocus: true,
			invalidateAll: true
		}).finally(() => {
			jenisLoading = false;
		});
	}

	async function handleExportPdf() {
		if (!browser || exporting) return;
		exporting = true;
		try {
			const { exportLaporanCatatanPdf } = await import('$lib/utils/export-pdf');
			await exportLaporanCatatanPdf(laporan);
		} catch (error) {
			console.error('Export PDF gagal:', error);
			alert('Gagal export PDF. Silakan coba lagi.');
		} finally {
			exporting = false;
		}
	}
</script>

<svelte:head>
	<title>Laporan Catatan Harian — Catatan Warung</title>
</svelte:head>

<AppShell memberName={data.member.nama} memberEmail={data.member.email}>
	<header
		class="relative overflow-hidden bg-gradient-to-br from-blue-600 via-indigo-600 to-violet-700 px-5 pb-8 pr-20 pt-[max(1.25rem,env(safe-area-inset-top))] text-white lg:px-8 lg:pb-10 lg:pr-8 lg:pt-6"
	>
		<div class="relative z-10 flex items-start justify-between gap-4">
			<div>
				<h1 class="text-xl font-bold lg:text-2xl">Laporan Catatan Harian</h1>
				<p class="mt-1 text-sm text-white/75">{laporan.warungNama}</p>
				<p class="text-xs text-white/50">{periodeLabel} · {laporan.jenisLabel}</p>
			</div>
			<LaporanExportButton exporting={exporting} showMobileFab={false} onclick={handleExportPdf} />
		</div>

		<div class="relative z-10 mt-5 grid grid-cols-3 gap-2 rounded-2xl bg-white/15 p-3 backdrop-blur-sm">
			<div>
				<p class="text-[10px] text-white/70">Pemasukan</p>
				<p class="text-sm font-bold lg:text-base">{formatRupiah(laporan.totalPendapatan)}</p>
			</div>
			<div>
				<p class="text-[10px] text-white/70">Pengeluaran</p>
				<p class="text-sm font-bold lg:text-base">{formatRupiah(laporan.totalPengeluaran)}</p>
			</div>
			<div>
				<p class="text-[10px] text-white/70">Saldo</p>
				<p class="text-sm font-bold lg:text-base">{formatRupiah(laporan.saldo)}</p>
			</div>
		</div>
	</header>

	<main class="page-content pb-24 lg:pb-8">
		<LaporanMenu />

		<LaporanDateFilter
			basePath="/laporan/catatan"
			tanggalAwal={laporan.tanggalAwal}
			tanggalAkhir={laporan.tanggalAkhir}
			extraParams={{ jenis: laporan.jenis }}
		/>

		<div class="flex gap-2 overflow-x-auto pb-1">
			{#each jenisOptions as option}
				<button
					type="button"
					class="btn btn-sm shrink-0 rounded-full {laporan.jenis === option.value
						? 'border-0 bg-blue-600 text-white'
						: 'btn-ghost bg-base-100'}"
					disabled={jenisLoading}
					onclick={() => setJenis(option.value)}
				>
					{option.label}
				</button>
			{/each}
		</div>

		<section class="card bg-base-100 shadow-xl">
			<div class="card-body gap-3 p-5">
				<div class="flex items-center justify-between">
					<h2 class="font-bold">Daftar Catatan</h2>
					<span class="badge badge-ghost">{laporan.jumlah} item</span>
				</div>

				{#if laporan.items.length === 0}
					<p class="py-8 text-center text-sm text-base-content/50">
						Tidak ada catatan pada periode dan filter ini.
					</p>
				{:else}
					<div class="overflow-x-auto">
						<table class="table table-sm">
							<thead>
								<tr class="text-xs">
									<th>Tanggal</th>
									<th>Jenis</th>
									<th>Kategori</th>
									<th>Deskripsi</th>
									<th class="text-right">Jumlah</th>
								</tr>
							</thead>
							<tbody>
								{#each laporan.items as item (item.id)}
									<tr class="hover">
										<td class="text-xs whitespace-nowrap">{item.tanggal}</td>
										<td>
											<span
												class="badge badge-xs {item.jenis === 'pendapatan'
													? 'badge-success'
													: 'badge-error'}"
											>
												{item.jenis === 'pendapatan' ? 'Masuk' : 'Keluar'}
											</span>
										</td>
										<td class="text-xs">{item.kategori}</td>
										<td class="max-w-[140px] truncate text-xs lg:max-w-xs">{item.deskripsi}</td>
										<td
											class="text-right text-xs font-semibold {item.jenis === 'pendapatan'
												? 'text-emerald-600'
												: 'text-rose-600'}"
										>
											{item.jenis === 'pendapatan' ? '+' : '-'}{formatRupiah(item.jumlah)}
										</td>
									</tr>
								{/each}
							</tbody>
						</table>
					</div>
				{/if}
			</div>
		</section>
	</main>

	<LaporanExportButton exporting={exporting} showHeader={false} onclick={handleExportPdf} />
</AppShell>
