<script lang="ts">
	import AppShell from '$lib/components/layout/AppShell.svelte';
	import { INTERVAL_LABEL, PRIVILEGE_DEFS } from '$lib/constants/privilege';
	import { formatRupiah } from '$lib/utils/format';
	import type { PageData } from './$types';
	import type { IntervalLangganan } from '$lib/types/langganan';

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

	let interval: IntervalLangganan = $state('bulanan');

	function hargaPaket(paketId: number): number {
		const paket = data.paketList.find((p) => p.id === paketId);
		return paket?.harga.find((h) => h.interval === interval)?.harga ?? 0;
	}

	function privilegeLabel(kode: string, nilai: string): string {
		const def = PRIVILEGE_DEFS.find((d) => d.kode === kode);
		if (!def) return '';
		if (def.tipe === 'boolean') return nilai === 'true' || nilai === '1' ? def.nama : '';
		if (nilai === '0') return `${def.nama}: Tak terbatas`;
		return `${def.nama}: ${nilai}`;
	}

	function isPaketAktif(kode: string): boolean {
		return data.entitlements.paketKode === kode;
	}

	function hematTahunan(bulanan: number, tahunan: number): number {
		if (!bulanan) return 0;
		return Math.round(((bulanan * 12 - tahunan) / (bulanan * 12)) * 100);
	}
</script>

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

<AppShell memberName={data.member.nama} memberEmail={data.member.email}>
	<header class="desktop-page-header">
		<div>
			<h1 class="text-2xl font-bold">Paket Langganan</h1>
			<p class="text-sm text-base-content/50">Pilih paket yang sesuai kebutuhan warung Anda</p>
		</div>
	</header>

	<header
		class="mobile-page-header bg-gradient-to-br from-violet-600 via-purple-600 to-indigo-700 lg:hidden"
	>
		<h1 class="text-xl font-bold">Paket Langganan</h1>
		<p class="text-sm text-white/70">Upgrade fitur warung Anda</p>
	</header>

	<main class="page-content">
		<div class="card bg-gradient-to-br from-violet-600 to-purple-700 text-white shadow-lg">
			<div class="card-body">
				<div class="flex flex-wrap items-center justify-between gap-4">
					<div>
						<p class="text-sm text-white/70">Paket Anda saat ini</p>
						<h2 class="text-2xl font-bold capitalize">{data.entitlements.paketNama}</h2>
						{#if data.langganan}
							<p class="mt-1 text-sm text-white/70">
								{INTERVAL_LABEL[data.langganan.interval]}
								{#if data.langganan.berakhir_at}
									· Berlaku sampai {new Date(data.langganan.berakhir_at).toLocaleDateString('id-ID')}
								{/if}
							</p>
						{:else}
							<p class="mt-1 text-sm text-white/70">Paket gratis — upgrade untuk fitur lebih lengkap</p>
						{/if}
					</div>
					<div class="rounded-xl bg-white/15 px-4 py-3 text-center">
						<p class="text-xs text-white/70">Transaksi bulan ini</p>
						<p class="text-xl font-bold">{data.transaksiBulanIni}</p>
					</div>
				</div>
			</div>
		</div>

		<div class="flex">
			<div class="inline-flex rounded-xl border border-base-300 bg-base-100 p-1 shadow-sm">
				<button
					type="button"
					class="rounded-lg px-5 py-2 text-sm font-semibold transition-colors {interval === 'bulanan'
						? 'bg-base-100 shadow'
						: 'text-base-content/50'}"
					onclick={() => (interval = 'bulanan')}
				>
					Bulanan
				</button>
				<button
					type="button"
					class="rounded-lg px-5 py-2 text-sm font-semibold transition-colors {interval === 'tahunan'
						? 'bg-base-100 shadow'
						: 'text-base-content/50'}"
					onclick={() => (interval = 'tahunan')}
				>
					Tahunan
					<span class="ml-1 text-xs text-emerald-600">Hemat</span>
				</button>
			</div>
		</div>

		<div class="grid gap-5 lg:grid-cols-2 xl:grid-cols-4">
			{#each data.paketList as paket}
				{@const hargaBulanan = paket.harga.find((h) => h.interval === 'bulanan')?.harga ?? 0}
				{@const hargaTahunan = paket.harga.find((h) => h.interval === 'tahunan')?.harga ?? 0}
				{@const harga = hargaPaket(paket.id)}
				<div
					class="card bg-base-100 shadow-md transition-all {isPaketAktif(paket.kode)
						? 'ring-2 ring-primary'
						: 'hover:shadow-xl'}"
				>
					<div class="card-body">
						<div class="flex items-center justify-between">
							<h3 class="text-lg font-bold">{paket.nama}</h3>
							{#if isPaketAktif(paket.kode)}
								<span class="badge badge-primary badge-sm">Aktif</span>
							{/if}
						</div>
						<p class="text-sm text-base-content/50">{paket.deskripsi}</p>

						<div class="my-4">
							<p class="text-3xl font-extrabold">
								{harga === 0 ? 'Gratis' : formatRupiah(harga)}
							</p>
							<p class="text-xs text-base-content/40">
								/ {interval === 'bulanan' ? 'bulan' : 'tahun'}
							</p>
							{#if interval === 'tahunan' && hargaBulanan > 0}
								<p class="mt-1 text-xs text-emerald-600">
									Hemat {hematTahunan(hargaBulanan, hargaTahunan)}% vs bulanan
								</p>
							{/if}
						</div>

						<ul class="space-y-2 text-sm">
							{#each paket.privileges as priv}
								{@const label = privilegeLabel(priv.kode, priv.nilai)}
								{#if label}
									<li class="flex items-start gap-2">
										<span class="text-emerald-500">✓</span>
										<span>{label}</span>
									</li>
								{/if}
							{/each}
						</ul>

						<div class="card-actions mt-4 justify-stretch">
							{#if isPaketAktif(paket.kode)}
								<button type="button" class="btn btn-disabled btn-block" disabled>Paket Saat Ini</button>
							{:else if paket.kode === 'free'}
								<button type="button" class="btn btn-ghost btn-block" disabled>Paket Dasar</button>
							{:else}
								<button
									type="button"
									class="btn btn-primary btn-block"
									onclick={() =>
										alert(
											`Untuk upgrade ke paket ${paket.nama} (${INTERVAL_LABEL[interval]} — ${formatRupiah(harga)}), hubungi admin atau lakukan pembayaran. Fitur pembayaran online akan segera tersedia.`
										)}
								>
									Pilih {paket.nama}
								</button>
							{/if}
						</div>
					</div>
				</div>
			{/each}
		</div>

		<div class="alert alert-info">
			<span>ℹ️</span>
			<span>
				Pembayaran langganan saat ini diaktifkan oleh admin setelah konfirmasi transfer.
				Hubungi tim support untuk upgrade paket.
			</span>
		</div>
	</main>
</AppShell>
