<script lang="ts">
	import { goto } from '$app/navigation';

	interface Props {
		basePath: string;
		tanggalAwal: string;
		tanggalAkhir: string;
		extraParams?: Record<string, string>;
		loading?: boolean;
	}

	let {
		basePath,
		tanggalAwal,
		tanggalAkhir,
		extraParams = {},
		loading = false
	}: Props = $props();

	let dari = $state(tanggalAwal);
	let sampai = $state(tanggalAkhir);

	$effect(() => {
		dari = tanggalAwal;
		sampai = tanggalAkhir;
	});

	function buildUrl(nextDari: string, nextSampai: string): string {
		const params = new URLSearchParams({ ...extraParams, dari: nextDari, sampai: nextSampai });
		return `${basePath}?${params.toString()}`;
	}

	function applyFilter() {
		if (loading || !dari) return;
		const end = sampai || dari;
		goto(buildUrl(dari, end), { replaceState: true, keepFocus: true, invalidateAll: true });
	}

	function setHariIni() {
		const today = new Date();
		const value = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
		dari = value;
		sampai = value;
		applyFilter();
	}
</script>

<div class="card bg-base-100 shadow-md">
	<div class="card-body gap-3 p-4 lg:p-5">
		<div class="flex flex-wrap items-end justify-between gap-3">
			<div>
				<h2 class="text-sm font-bold lg:text-base">Filter Tanggal</h2>
				<p class="text-xs text-base-content/50">Pilih rentang tanggal laporan</p>
			</div>
			<button type="button" class="btn btn-ghost btn-xs rounded-full" disabled={loading} onclick={setHariIni}>
				Hari Ini
			</button>
		</div>

		<div class="grid grid-cols-2 gap-3 lg:max-w-xl">
			<div class="form-control">
				<label class="label py-0" for="laporan-dari">
					<span class="label-text text-xs font-semibold">Dari</span>
				</label>
				<input
					id="laporan-dari"
					type="date"
					class="input input-bordered input-sm w-full rounded-xl"
					bind:value={dari}
					disabled={loading}
					onchange={applyFilter}
				/>
			</div>
			<div class="form-control">
				<label class="label py-0" for="laporan-sampai">
					<span class="label-text text-xs font-semibold">Sampai</span>
				</label>
				<input
					id="laporan-sampai"
					type="date"
					class="input input-bordered input-sm w-full rounded-xl"
					bind:value={sampai}
					disabled={loading}
					onchange={applyFilter}
				/>
			</div>
		</div>
	</div>
</div>
