<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 { penjualanKategoriIcon } from '$lib/constants/outline-icon-map';
	import type { FilterPeriode } from '$lib/types/transaksi';
	import { confirmBeforeSubmit } from '$lib/utils/confirm';
	import { formatRupiah, formatWaktu } from '$lib/utils/format';
	import type { PageData } from './$types';

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

	const filters: { value: FilterPeriode; label: string }[] = [
		{ value: 'hari', label: 'Hari Ini' },
		{ value: 'minggu', label: 'Minggu Ini' },
		{ value: 'semua', label: 'Semua' }
	];

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

	function setFilter(filter: FilterPeriode) {
		goto(`/transaksi/penjualan?filter=${filter}`, { replaceState: true, keepFocus: true });
	}
</script>

<svelte:head>
	<title>Penjualan — Catatan Warung</title>
</svelte:head>

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

<AppShell memberName={data.member.nama} memberEmail={data.member.email}>
	<!-- Mobile Header -->
	<header
		class="relative overflow-hidden bg-gradient-to-br from-emerald-600 via-teal-600 to-cyan-700 px-5 pb-6 pr-20 pt-[max(1.25rem,env(safe-area-inset-top))] text-white lg:hidden"
	>
		<div class="flex items-center gap-2">
			<a href="/transaksi" class="btn-icon-back" aria-label="Kembali">
				<OutlineIcon name="arrow-left" size="sm" />
			</a>
			<div>
				<h1 class="text-xl font-bold">Penjualan</h1>
				<p class="text-sm text-white/70">{data.jumlah} transaksi tercatat</p>
			</div>
		</div>
		<div class="mt-4 rounded-2xl bg-white/15 p-4 backdrop-blur-sm">
			<p class="text-sm text-white/70">Total Penjualan</p>
			<p class="text-2xl font-extrabold">{formatRupiah(data.total)}</p>
		</div>
	</header>

	<!-- Desktop Header -->
	<header class="hidden items-center justify-between border-b border-base-300 bg-base-100 px-8 py-5 lg:flex">
		<div class="flex items-center gap-4">
			<a href="/transaksi" class="btn btn-ghost btn-sm">← Transaksi</a>
			<div>
				<h1 class="text-2xl font-bold">Daftar Penjualan</h1>
				<p class="text-sm text-base-content/50">Kelola dan pantau semua transaksi penjualan warung</p>
			</div>
		</div>
		<a
			href="/transaksi/penjualan/tambah"
			class="btn border-0 bg-gradient-to-r from-emerald-500 to-teal-600 text-white hover:from-emerald-600 hover:to-teal-700"
		>
			➕ Tambah Penjualan
		</a>
	</header>

	<main class="page-content">
		<!-- Filter Tabs -->
		<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-emerald-600 text-white'
						: 'btn-ghost bg-base-100'}"
					onclick={() => setFilter(f.value)}
				>
					{f.label}
				</button>
			{/each}
		</div>

		<!-- Desktop Stats -->
		<div class="hidden gap-4 lg:grid lg:grid-cols-3">
			<div class="card bg-base-100 shadow-md">
				<div class="card-body p-5">
					<p class="text-sm text-base-content/50">Total Penjualan</p>
					<p class="text-2xl font-bold text-emerald-600">{formatRupiah(data.total)}</p>
				</div>
			</div>
			<div class="card bg-base-100 shadow-md">
				<div class="card-body p-5">
					<p class="text-sm text-base-content/50">Jumlah Transaksi</p>
					<p class="text-2xl font-bold">{data.jumlah}</p>
				</div>
			</div>
			<div class="card bg-base-100 shadow-md">
				<div class="card-body p-5">
					<p class="text-sm text-base-content/50">Rata-rata / Transaksi</p>
					<p class="text-2xl font-bold">
						{formatRupiah(data.jumlah > 0 ? Math.round(data.total / data.jumlah) : 0)}
					</p>
				</div>
			</div>
		</div>

		<!-- List -->
		{#if data.penjualan.length === 0}
			<div class="card bg-base-100 shadow-md">
				<div class="card-body items-center py-16 text-center">
					<div class="text-5xl">📭</div>
					<h2 class="mt-4 text-lg font-bold">Belum ada penjualan</h2>
					<p class="text-sm text-base-content/50">
						Mulai catat penjualan pertama warung Anda sekarang.
					</p>
					<a
						href="/transaksi/penjualan/tambah"
						class="btn mt-4 border-0 bg-gradient-to-r from-emerald-500 to-teal-600 text-white"
					>
						➕ Tambah Penjualan
					</a>
				</div>
			</div>
		{:else}
			<div class="grid gap-3 lg:grid-cols-2">
				{#each data.penjualan as item (item.id)}
					<div
						class="card bg-base-100 shadow-md transition-shadow hover:shadow-lg"
					>
						<div class="card-body flex-row items-center gap-4 p-4">
							<IconRing tone="emerald" size="md">
								<OutlineIcon name={penjualanKategoriIcon(item.kategori)} size="md" />
							</IconRing>
							<div class="min-w-0 flex-1">
								<p class="truncate font-semibold">{item.deskripsi}</p>
								<p class="text-xs text-base-content/50">
									{item.kategori} · {formatWaktu(item.created_at)}
									{#if item.barang_nama && item.qty}
										· <span class="text-violet-600">📦 {item.barang_nama} ×{item.qty}</span>
									{/if}
								</p>
							</div>
							<div class="flex shrink-0 flex-col items-end gap-1">
								<p class="font-bold text-emerald-600">{formatRupiah(item.jumlah)}</p>
								<form
									method="POST"
									action="?/hapus"
									use:enhance={() => {
										deletingId = item.id;
										return async ({ update }) => {
											deletingId = null;
											await update();
										};
									}}
								>
									<input type="hidden" name="id" value={item.id} />
									<button
										type="submit"
										class="btn btn-ghost btn-xs text-rose-500"
										disabled={deletingId === item.id}
										onclick={(e) =>
											confirmBeforeSubmit(e, {
												title: 'Hapus Penjualan',
												message: 'Transaksi ini akan dihapus permanen. Lanjutkan?',
												confirmText: 'Hapus',
												tone: 'danger'
											})}
									>
										{#if deletingId === item.id}
											<span class="loading loading-spinner loading-xs"></span>
										{:else}
											Hapus
										{/if}
									</button>
								</form>
							</div>
						</div>
					</div>
				{/each}
			</div>
		{/if}
	</main>

	<!-- Mobile FAB -->
	<a
		href="/transaksi/penjualan/tambah"
		class="btn-fab-outline btn-fab-outline-emerald fixed bottom-20 right-4 z-40 text-2xl lg:hidden"
		aria-label="Tambah penjualan"
	>
		<OutlineIcon name="plus" size="lg" />
	</a>
</AppShell>
