<script lang="ts">
	import { goto } from '$app/navigation';
	import AppShell from '$lib/components/layout/AppShell.svelte';
	import FlashToast from '$lib/components/ui/FlashToast.svelte';
	import OutlineIcon from '$lib/components/ui/OutlineIcon.svelte';
	import type { PageData } from './$types';

	let { data }: { data: PageData } = $props();
</script>

<svelte:head>
	<title>Stok Opname — Catatan Warung</title>
</svelte:head>

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

<AppShell memberName={data.member.nama} memberEmail={data.member.email}>
	<header class="mobile-subpage-header bg-gradient-to-r from-violet-600 to-purple-600">
		<div class="flex items-center gap-3">
			<a href="/stok" class="btn-icon-back">
				<OutlineIcon name="arrow-left" size="sm" />
			</a>
			<div class="flex-1">
				<h1 class="text-lg font-bold lg:text-2xl">Stok Opname</h1>
				<p class="text-xs text-white/70 lg:text-sm">Cocokkan stok fisik dengan sistem</p>
			</div>
			<a href="/stok/opname/tambah" class="btn-outline-on-dark hidden gap-1.5 lg:inline-flex">
				<OutlineIcon name="plus" size="xs" />
				Opname Baru
			</a>
		</div>
		<a href="/stok/opname/tambah" class="btn-outline-on-dark gap-1.5 lg:hidden">
			<OutlineIcon name="plus" size="xs" />
			Opname Baru
		</a>
	</header>

	<main class="page-content">
		<div class="surface-violet rounded-xl p-4">
			<p class="text-sm font-semibold">Apa itu stok opname?</p>
			<p class="mt-1 text-xs text-white/80">
				Hitung stok fisik di warung, masukkan angka sebenarnya. Sistem otomatis menyesuaikan selisih.
			</p>
		</div>

		{#if data.opnameList.length === 0}
			<div class="card bg-base-100 shadow-md">
				<div class="card-body items-center py-12 text-center">
					<OutlineIcon name="clipboard" size="xl" class="text-base-content/30" />
					<p class="mt-3 font-bold">Belum ada riwayat opname</p>
					<a href="/stok/opname/tambah" class="btn mt-4 border-0 bg-violet-600 text-white">➕ Mulai Opname</a>
				</div>
			</div>
		{:else}
			<div class="flex flex-col gap-3">
				{#each data.opnameList as opname (opname.id)}
					<button
						type="button"
						class="card bg-base-100 text-left shadow-md transition-shadow hover:shadow-lg"
						onclick={() => goto(`/stok/opname/${opname.id}`)}
					>
						<div class="card-body gap-2 p-4">
							<div class="flex items-center justify-between">
								<p class="font-bold">Opname {opname.tanggal}</p>
								<span class="badge badge-sm {opname.jumlah_selisih > 0 ? 'badge-warning' : 'badge-success'}">
									{opname.jumlah_selisih > 0 ? `${opname.jumlah_selisih} selisih` : 'Sesuai'}
								</span>
							</div>
							<p class="text-xs text-base-content/50">
								{opname.jumlah_item} barang dicek
								{#if opname.keterangan} · {opname.keterangan}{/if}
							</p>
						</div>
					</button>
				{/each}
			</div>
		{/if}
	</main>
</AppShell>
