<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 type { IconRingTone } from '$lib/components/ui/IconRing.svelte';
	import type { OutlineIconName } from '$lib/components/ui/OutlineIcon.svelte';
	import type { FilterStok, JenisMutasi } from '$lib/types/stok';
	import { confirmBeforeSubmit } from '$lib/utils/confirm';
	import { formatRupiah } from '$lib/utils/format';
	import { getTodayDateString } from '$lib/utils/parse';
	import type { ActionData, PageData } from './$types';

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

	const filters: { value: FilterStok; label: string; icon: OutlineIconName }[] = [
		{ value: 'semua', label: 'Semua', icon: 'package' },
		{ value: 'menipis', label: 'Menipis', icon: 'warning' },
		{ value: 'habis', label: 'Habis', icon: 'circle' },
		{ value: 'aktif', label: 'Aktif', icon: 'check' }
	];

	let actionId = $state<number | null>(null);
	let mutasiBarangId = $state<number | null>(null);
	let mutasiJenis = $state<JenisMutasi>('masuk');
	let mutasiJumlah = $state('1');
	let mutasiKeterangan = $state('');
	let mutasiTanggal = $state(getTodayDateString());

	function setFilter(filter: FilterStok) {
		const params = new URLSearchParams();
		params.set('filter', filter);
		if (data.kategoriFilter) params.set('kategori', data.kategoriFilter);
		goto(`/stok?${params.toString()}`, { replaceState: true, keepFocus: true });
	}

	function setKategori(kategori: string) {
		const params = new URLSearchParams();
		params.set('filter', data.filter);
		if (kategori) params.set('kategori', kategori);
		goto(`/stok?${params.toString()}`, { replaceState: true, keepFocus: true });
	}

	function openMutasi(id: number, jenis: JenisMutasi) {
		mutasiBarangId = id;
		mutasiJenis = jenis;
		mutasiJumlah = '1';
		mutasiKeterangan = '';
		mutasiTanggal = getTodayDateString();
	}

	function closeMutasi() {
		mutasiBarangId = null;
	}

	function statusBadge(status: string) {
		if (status === 'habis') return 'badge-error';
		if (status === 'menipis') return 'badge-warning';
		return 'badge-success';
	}

	function statusLabel(status: string) {
		if (status === 'habis') return 'Habis';
		if (status === 'menipis') return 'Menipis';
		return 'Aman';
	}

	function statusStokTone(status: string): IconRingTone {
		if (status === 'habis') return 'rose';
		if (status === 'menipis') return 'amber';
		return 'emerald';
	}

	function mutasiIcon(jenis: JenisMutasi) {
		if (jenis === 'masuk') return '📥';
		if (jenis === 'keluar') return '📤';
		return '⚖️';
	}

	$effect(() => {
		if (form?.mutasiSuccess) {
			closeMutasi();
		}
	});
</script>

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

<FlashToast message={data.success ? 'Data stok berhasil disimpan!' : undefined} />
<FlashToast message={form?.mutasiSuccess ? 'Mutasi stok berhasil disimpan!' : undefined} />
<FlashToast message={form?.mutasiError} type="error" />

<AppShell memberName={data.member.nama} memberEmail={data.member.email}>
	<header
		class="mobile-page-header bg-gradient-to-r from-indigo-600 via-violet-600 to-purple-600"
	>
		<div>
			<h1 class="text-xl font-bold">Stok Barang</h1>
			<p class="text-sm text-white/70">{data.summary.totalBarang} barang · {formatRupiah(data.summary.nilaiStok)}</p>
		</div>
		<div class="mt-3 flex gap-2">
			<a href="/stok/opname" class="btn-outline-on-dark flex-1 gap-1.5">
				<OutlineIcon name="clipboard" size="xs" />
				Opname
			</a>
			<a href="/stok/tambah" class="btn-outline-on-dark flex-1 gap-1.5">
				<OutlineIcon name="plus" size="xs" />
				Tambah
			</a>
		</div>
	</header>

	<header class="desktop-page-header">
		<div>
			<h1 class="text-2xl font-bold">Stok Barang</h1>
			<p class="text-sm text-base-content/50">
				{data.summary.totalBarang} barang · Nilai stok {formatRupiah(data.summary.nilaiStok)}
			</p>
		</div>
		<div class="flex gap-2">
			<a href="/stok/opname" class="btn btn-outline btn-sm">📋 Stok Opname</a>
			<a href="/stok/tambah" class="btn btn-sm border-0 bg-gradient-to-r from-violet-600 to-purple-600 text-white">
				➕ Tambah Barang
			</a>
		</div>
	</header>

	<main class="page-content">
		<div class="grid grid-cols-3 gap-2 lg:grid-cols-4 lg:gap-3">
			<div class="card border-0 bg-gradient-to-br from-indigo-600 to-violet-600 text-white shadow-sm">
				<div class="card-body items-center p-2 text-center lg:items-start lg:p-4 lg:text-left">
					<p class="text-[10px] leading-tight text-white/75 lg:text-xs">Total Barang</p>
					<p class="text-lg font-bold lg:text-2xl">{data.summary.totalBarang}</p>
				</div>
			</div>
			<div class="card border-0 bg-gradient-to-br from-amber-500 to-orange-500 text-white shadow-sm">
				<div class="card-body items-center p-2 text-center lg:items-start lg:p-4 lg:text-left">
					<p class="text-[10px] leading-tight text-white/75 lg:text-xs">Stok Menipis</p>
					<p class="text-lg font-bold lg:text-2xl">{data.summary.totalStokMenipis}</p>
				</div>
			</div>
			<div class="card border-0 bg-gradient-to-br from-rose-600 to-pink-600 text-white shadow-sm">
				<div class="card-body items-center p-2 text-center lg:items-start lg:p-4 lg:text-left">
					<p class="text-[10px] leading-tight text-white/75 lg:text-xs">Stok Habis</p>
					<p class="text-lg font-bold lg:text-2xl">{data.summary.totalStokHabis}</p>
				</div>
			</div>
			<div class="card col-span-3 border-0 bg-gradient-to-br from-emerald-600 to-teal-600 text-white shadow-sm lg:col-span-1">
				<div class="card-body p-3 lg:p-4">
					<p class="text-xs text-white/75">Nilai Stok</p>
					<p class="text-xl font-bold lg:text-2xl">{formatRupiah(data.summary.nilaiStok)}</p>
				</div>
			</div>
		</div>

		<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-violet-600 text-white'
						: 'btn-ghost bg-base-100'}"
					onclick={() => setFilter(f.value)}
				>
					<OutlineIcon name={f.icon} size="xs" />
					{f.label}
				</button>
			{/each}
		</div>

		{#if data.kategoriList.length > 0}
			<div class="flex gap-2 overflow-x-auto pb-1">
				<button
					type="button"
					class="btn btn-xs shrink-0 rounded-full {!data.kategoriFilter
						? 'border-0 bg-indigo-600 text-white'
						: 'btn-ghost bg-base-100'}"
					onclick={() => setKategori('')}
				>
					Semua Kategori
				</button>
				{#each data.kategoriList as kat}
					<button
						type="button"
						class="btn btn-xs shrink-0 rounded-full {data.kategoriFilter === kat
							? 'border-0 bg-indigo-600 text-white'
							: 'btn-ghost bg-base-100'}"
						onclick={() => setKategori(kat)}
					>
						{kat}
					</button>
				{/each}
			</div>
		{/if}

		{#if data.items.length === 0}
			<div class="card bg-base-100 shadow-md">
				<div class="card-body items-center py-12 text-center">
					<OutlineIcon name="package" size="xl" class="text-base-content/30" />
					<p class="mt-3 font-bold">Belum ada barang di stok</p>
					<p class="text-sm text-base-content/50">Tambahkan barang pertama untuk mulai mengelola inventori</p>
					<a href="/stok/tambah" class="btn mt-4 border-0 bg-violet-600 text-white">➕ Tambah Barang</a>
				</div>
			</div>
		{:else}
			<div class="grid gap-3 lg:grid-cols-2 xl:grid-cols-3">
				{#each data.items as item (item.id)}
					<div class="card bg-base-100 shadow-md {!item.is_aktif ? 'opacity-60' : ''}">
						<div class="card-body gap-3 p-4">
							<div class="flex items-start justify-between gap-3">
								<div class="flex min-w-0 flex-1 items-center gap-3">
									<IconRing tone={statusStokTone(item.status_stok)} size="sm">
										<OutlineIcon name="package" size="sm" />
									</IconRing>
									<div class="min-w-0">
										<p class="truncate font-bold">{item.nama}</p>
										<p class="text-xs text-base-content/50">
											{item.kategori} · {item.satuan}
											{#if !item.is_aktif} · Nonaktif{/if}
										</p>
									</div>
								</div>
								<span class="badge badge-sm {statusBadge(item.status_stok)}">
									{statusLabel(item.status_stok)}
								</span>
							</div>

							<div class="grid grid-cols-3 gap-2 rounded-xl bg-base-200/50 p-3">
								<div>
									<p class="text-[10px] text-base-content/50">Stok</p>
									<p class="text-lg font-bold">{item.stok}</p>
									<p class="text-[10px] text-base-content/40">min. {item.stok_minimum}</p>
								</div>
								<div>
									<p class="text-[10px] text-base-content/50">Harga Beli</p>
									<p class="text-sm font-semibold">
										{item.harga_beli != null ? formatRupiah(item.harga_beli) : '—'}
									</p>
								</div>
								<div>
									<p class="text-[10px] text-base-content/50">Harga Jual</p>
									<p class="text-sm font-semibold text-emerald-600">
										{item.harga_jual != null ? formatRupiah(item.harga_jual) : '—'}
									</p>
								</div>
							</div>

							{#if item.deskripsi}
								<p class="text-xs text-base-content/50">{item.deskripsi}</p>
							{/if}

							<div class="flex flex-wrap gap-2">
								<button
									type="button"
									class="btn btn-success btn-sm flex-1 text-white"
									onclick={() => openMutasi(item.id, 'masuk')}
								>
									📥 Masuk
								</button>
								<button
									type="button"
									class="btn btn-warning btn-sm flex-1 text-white"
									onclick={() => openMutasi(item.id, 'keluar')}
									disabled={item.stok <= 0}
								>
									📤 Keluar
								</button>
								<a href="/stok/{item.id}/edit" class="btn btn-outline btn-sm">✏️ Edit</a>
								<form
									method="POST"
									action="?/hapus"
									use:enhance={() => {
										actionId = item.id;
										return async ({ update }) => {
											actionId = null;
											await update();
										};
									}}
								>
									<input type="hidden" name="id" value={item.id} />
									<button
										type="submit"
										class="btn btn-outline btn-sm border-rose-500 text-rose-600 hover:border-rose-600 hover:bg-rose-50 hover:text-rose-700"
										disabled={actionId === item.id}
										onclick={(e) =>
											confirmBeforeSubmit(e, {
												title: 'Hapus Barang',
												message: `Hapus "${item.nama}" dari stok? Tindakan ini tidak bisa dibatalkan.`,
												confirmText: 'Hapus',
												tone: 'danger'
											})}
									>
										Hapus
									</button>
								</form>
							</div>

							{#if mutasiBarangId === item.id}
								<form
									method="POST"
									action="?/mutasi"
									class="surface-violet rounded-xl border border-violet-400 p-4"
									use:enhance={() => {
										actionId = item.id;
										return async ({ update }) => {
											actionId = null;
											await update();
										};
									}}
								>
									<input type="hidden" name="barang_id" value={item.id} />
									<input type="hidden" name="jenis" value={mutasiJenis} />

									<p class="mb-3 text-sm font-bold">
										{mutasiIcon(mutasiJenis)}
										Stok {mutasiJenis === 'masuk' ? 'Masuk' : 'Keluar'} — {item.nama}
									</p>

									<div class="flex flex-col gap-3">
										<div class="form-control">
											<label class="label py-0" for="mutasi_jumlah_{item.id}">
												<span class="label-text font-semibold">Jumlah ({item.satuan})</span>
											</label>
											<input
												id="mutasi_jumlah_{item.id}"
												name="jumlah"
												type="number"
												min="1"
												class="input input-bordered w-full bg-base-100"
												bind:value={mutasiJumlah}
												required
											/>
										</div>
										<div class="form-control">
											<label class="label py-0" for="mutasi_ket_{item.id}">
												<span class="label-text font-semibold">Keterangan</span>
											</label>
											<input
												id="mutasi_ket_{item.id}"
												name="keterangan"
												type="text"
												class="input input-bordered w-full bg-base-100"
												placeholder={mutasiJenis === 'masuk'
													? 'Contoh: Restock dari supplier'
													: 'Contoh: Terjual / dipakai'}
												bind:value={mutasiKeterangan}
											/>
										</div>
										<div class="form-control">
											<label class="label py-0" for="mutasi_tgl_{item.id}">
												<span class="label-text font-semibold">Tanggal</span>
											</label>
											<input
												id="mutasi_tgl_{item.id}"
												name="tanggal"
												type="date"
												class="input input-bordered w-full bg-base-100"
												bind:value={mutasiTanggal}
												max={getTodayDateString()}
												required
											/>
										</div>
										<div class="flex gap-2">
											<button type="button" class="btn btn-ghost btn-sm flex-1" onclick={closeMutasi}>
												Batal
											</button>
											<button
												type="submit"
												class="btn btn-sm flex-1 border-0 bg-violet-600 text-white"
												disabled={actionId === item.id}
											>
												{actionId === item.id ? 'Menyimpan...' : 'Simpan Mutasi'}
											</button>
										</div>
									</div>
								</form>
							{/if}
						</div>
					</div>
				{/each}
			</div>
		{/if}

		{#if data.mutasiTerbaru.length > 0}
			<section class="card bg-base-100 shadow-md">
				<div class="card-body gap-3 p-4">
					<h2 class="font-bold">Riwayat Mutasi Terbaru</h2>
					<div class="divide-y divide-base-200">
						{#each data.mutasiTerbaru as mutasi (mutasi.id)}
							<div class="flex items-center justify-between gap-3 py-3 first:pt-0 last:pb-0">
								<div class="min-w-0">
									<p class="truncate text-sm font-semibold">
										{mutasiIcon(mutasi.jenis)} {mutasi.barang_nama}
									</p>
									<p class="text-xs text-base-content/50">
										{mutasi.jenis === 'masuk' ? '+' : mutasi.jenis === 'keluar' ? '-' : '='}
										{mutasi.jumlah} · {mutasi.stok_sebelum} → {mutasi.stok_sesudah}
										{#if mutasi.keterangan} · {mutasi.keterangan}{/if}
									</p>
								</div>
								<span class="shrink-0 text-xs text-base-content/40">{mutasi.tanggal}</span>
							</div>
						{/each}
					</div>
				</div>
			</section>
		{/if}
	</main>
</AppShell>
