<script lang="ts">
	import { browser } from '$app/environment';
	import { goto } from '$app/navigation';
	import { page } from '$app/state';
	import AppShell from '$lib/components/layout/AppShell.svelte';
	import LaporanExportButton from '$lib/components/laporan/LaporanExportButton.svelte';
	import LaporanMenu from '$lib/components/laporan/LaporanMenu.svelte';
	import type { PeriodeLaporan } from '$lib/types/laporan';
	import { formatRupiah, formatRupiahShort } from '$lib/utils/format';
	import type { PageData } from './$types';

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

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

	const laporan = $derived(data.laporan);
	const ringkasan = $derived(laporan.ringkasan);
	const harian = $derived(laporan.harian);
	const maxHarian = $derived(Math.max(...harian.map((h) => Math.max(h.penjualan, h.pengeluaran)), 1));

	const periodeOptions: { value: PeriodeLaporan; label: string }[] = [
		{ value: 'hari', label: 'Hari Ini' },
		{ value: 'minggu', label: 'Minggu Ini' },
		{ value: 'bulan', label: 'Bulan Ini' },
		{ value: 'semua', label: 'Semua' }
	];

	function setPeriode(periode: PeriodeLaporan) {
		if (laporan.periode === periode || periodeLoading) return;
		periodeLoading = true;
		goto(`/laporan?periode=${periode}`, { replaceState: true, keepFocus: true, invalidateAll: true }).finally(
			() => {
				periodeLoading = false;
			}
		);
	}

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

	function formatTanggal(dateStr: string): string {
		return new Date(dateStr).toLocaleDateString('id-ID', {
			day: 'numeric',
			month: 'short',
			year: 'numeric'
		});
	}
</script>

<svelte:head>
	<title>Laporan — 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="pointer-events-none absolute -right-12 -top-12 h-48 w-48 rounded-full bg-white/10 blur-3xl"></div>
		<div class="relative z-10 flex items-start justify-between gap-4">
			<div>
				<h1 class="text-xl font-bold lg:text-2xl">Laporan Keuangan</h1>
				<p class="mt-1 text-sm text-white/75">{laporan.warungNama}</p>
				<p class="text-xs text-white/50">
					{laporan.periodeLabel} · {formatTanggal(laporan.tanggalAwal)} — {formatTanggal(laporan.tanggalAkhir)}
				</p>
			</div>
			<LaporanExportButton exporting={exporting} showMobileFab={false} onclick={handleExportPdf} />
		</div>

		<div class="relative z-10 mt-5 rounded-2xl bg-white/15 p-4 backdrop-blur-sm">
			<p class="text-xs text-white/70">Saldo Bersih</p>
			<p class="text-3xl font-extrabold">{formatRupiah(ringkasan.saldo)}</p>
			<p class="mt-1 text-xs text-white/60">
				Pendapatan {formatRupiahShort(ringkasan.totalPendapatan)} − Pengeluaran {formatRupiahShort(ringkasan.totalPengeluaran)}
			</p>
		</div>
	</header>

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

		<div class="flex items-center gap-2 overflow-x-auto pb-1">
			{#each periodeOptions as p}
				<button
					type="button"
					class="btn btn-sm shrink-0 rounded-full {laporan.periode === p.value
						? 'border-0 bg-indigo-600 text-white'
						: 'btn-ghost bg-base-100'}"
					disabled={periodeLoading}
					onclick={() => setPeriode(p.value)}
				>
					{p.label}
				</button>
			{/each}
			{#if periodeLoading}
				<span class="loading loading-spinner loading-xs text-indigo-600"></span>
			{/if}
		</div>

		<!-- Ringkasan -->
		<section class="grid grid-cols-2 gap-3 lg:grid-cols-4">
			<div class="card bg-base-100 shadow-md">
				<div class="card-body gap-1 p-4">
					<p class="text-xs text-base-content/50">Penjualan</p>
					<p class="text-lg font-bold text-emerald-600">{formatRupiahShort(ringkasan.pendapatanPenjualan)}</p>
					<p class="text-[10px] text-base-content/40">{ringkasan.jumlahPenjualan} transaksi</p>
				</div>
			</div>
			<div class="card bg-base-100 shadow-md">
				<div class="card-body gap-1 p-4">
					<p class="text-xs text-base-content/50">Pemasukan Lain</p>
					<p class="text-lg font-bold text-teal-600">{formatRupiahShort(ringkasan.pendapatanLain)}</p>
				</div>
			</div>
			<div class="card bg-base-100 shadow-md">
				<div class="card-body gap-1 p-4">
					<p class="text-xs text-base-content/50">Pengeluaran</p>
					<p class="text-lg font-bold text-rose-600">{formatRupiahShort(ringkasan.totalPengeluaran)}</p>
				</div>
			</div>
			<div class="card bg-base-100 shadow-md">
				<div class="card-body gap-1 p-4">
					<p class="text-xs text-base-content/50">Total Transaksi</p>
					<p class="text-lg font-bold">{ringkasan.jumlahTransaksi}</p>
				</div>
			</div>
		</section>

		<!-- Grafik Harian -->
		{#if harian.length > 0}
			<section class="card bg-base-100 shadow-xl">
				<div class="card-body gap-4 p-5 lg:p-6">
					<h2 class="text-base font-bold lg:text-lg">Tren Harian</h2>
					<div class="flex h-44 items-end justify-between gap-1 sm:gap-2">
						{#each harian as day (day.date)}
							<div class="group flex flex-1 flex-col items-center gap-1">
								<div class="flex h-full w-full max-w-12 items-end justify-center gap-0.5">
									<div
										class="w-2 rounded-t bg-emerald-400 sm:w-3"
										style="height: {Math.max((day.penjualan / maxHarian) * 100, day.penjualan > 0 ? 6 : 2)}%"
										title="Penjualan: {formatRupiah(day.penjualan)}"
									></div>
									<div
										class="w-2 rounded-t bg-rose-400 sm:w-3"
										style="height: {Math.max((day.pengeluaran / maxHarian) * 100, day.pengeluaran > 0 ? 6 : 2)}%"
										title="Pengeluaran: {formatRupiah(day.pengeluaran)}"
									></div>
								</div>
								<p class="text-[9px] font-medium text-base-content/60 sm:text-[10px]">{day.label}</p>
							</div>
						{/each}
					</div>
					<div class="flex justify-center gap-6 text-xs">
						<span class="flex items-center gap-1"><span class="h-3 w-3 rounded bg-emerald-400"></span> Penjualan</span>
						<span class="flex items-center gap-1"><span class="h-3 w-3 rounded bg-rose-400"></span> Pengeluaran</span>
					</div>
				</div>
			</section>
		{/if}

		<!-- Kategori -->
		<section class="grid gap-5 lg:grid-cols-2">
			<div class="card bg-base-100 shadow-md">
				<div class="card-body gap-3 p-5">
					<h2 class="font-bold text-emerald-700">Penjualan per Kategori</h2>
					{#if laporan.kategoriPenjualan.length === 0}
						<p class="py-4 text-center text-sm text-base-content/50">Tidak ada data</p>
					{:else}
						{#each laporan.kategoriPenjualan as kat}
							<div>
								<div class="mb-1 flex justify-between text-sm">
									<span>{kat.kategori}</span>
									<span class="font-semibold">{formatRupiahShort(kat.total)}</span>
								</div>
								<div class="h-2 overflow-hidden rounded-full bg-base-200">
									<div class="h-full rounded-full bg-emerald-500" style="width: {kat.persen}%"></div>
								</div>
							</div>
						{/each}
					{/if}
				</div>
			</div>

			<div class="card bg-base-100 shadow-md">
				<div class="card-body gap-3 p-5">
					<h2 class="font-bold text-rose-700">Pengeluaran per Kategori</h2>
					{#if laporan.kategoriPengeluaran.length === 0}
						<p class="py-4 text-center text-sm text-base-content/50">Tidak ada data</p>
					{:else}
						{#each laporan.kategoriPengeluaran as kat}
							<div>
								<div class="mb-1 flex justify-between text-sm">
									<span>{kat.kategori}</span>
									<span class="font-semibold">{formatRupiahShort(kat.total)}</span>
								</div>
								<div class="h-2 overflow-hidden rounded-full bg-base-200">
									<div class="h-full rounded-full bg-rose-500" style="width: {kat.persen}%"></div>
								</div>
							</div>
						{/each}
					{/if}
				</div>
			</div>
		</section>

		<!-- Daftar Transaksi -->
		<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 Transaksi</h2>
					<span class="badge badge-ghost">{laporan.transaksi.length} item</span>
				</div>
				{#if laporan.transaksi.length === 0}
					<p class="py-8 text-center text-sm text-base-content/50">Belum ada transaksi pada periode 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.transaksi as trx}
									<tr class="hover">
										<td class="text-xs whitespace-nowrap">{formatTanggal(trx.tanggal)}</td>
										<td>
											<span class="badge badge-xs {trx.jenis === 'pendapatan' ? 'badge-success' : 'badge-error'}">
												{trx.jenis === 'pendapatan' ? 'Masuk' : 'Keluar'}
											</span>
										</td>
										<td class="text-xs">{trx.kategori}</td>
										<td class="max-w-[140px] truncate text-xs lg:max-w-xs">{trx.deskripsi}</td>
										<td class="text-right text-xs font-semibold {trx.jenis === 'pendapatan' ? 'text-emerald-600' : 'text-rose-600'}">
											{trx.jenis === 'pendapatan' ? '+' : '-'}{formatRupiah(trx.jumlah)}
										</td>
									</tr>
								{/each}
							</tbody>
						</table>
					</div>
				{/if}
			</div>
		</section>

		<!-- Hutang Piutang -->
		{#if laporan.hutangPiutang.length > 0}
			<section class="card bg-base-100 shadow-md">
				<div class="card-body gap-2.5 px-3 py-4 lg:px-4">
					<h2 class="font-bold text-amber-700">Hutang & Piutang</h2>
					<div class="flex flex-col gap-2">
						{#each laporan.hutangPiutang as hp}
							<div class="flex items-start gap-2 rounded-xl bg-base-200/60 px-2.5 py-2">
								<div class="min-w-0 flex-1 text-left">
									<p class="text-sm leading-snug font-semibold break-words">{hp.nama}</p>
									<p class="mt-0.5 text-xs leading-snug text-base-content/50 capitalize break-words">
										{hp.jenis} · {hp.status === 'lunas' ? 'Lunas' : 'Belum lunas'}
									</p>
								</div>
								<p
									class="shrink-0 pt-0.5 text-right text-sm font-bold whitespace-nowrap {hp.jenis === 'hutang'
										? 'text-rose-600'
										: 'text-emerald-600'}"
								>
									{formatRupiah(hp.sisa)}
								</p>
							</div>
						{/each}
					</div>
				</div>
			</section>
		{/if}
	</main>

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