<script lang="ts">
	import { goto } from '$app/navigation';
	import { page } from '$app/stores';
	import { DEVICE_CATEGORIES, DEVICE_CONDITIONS } from '$lib/constants.js';

	let { data } = $props();

	let search = $state(data.filters.search ?? '');

	function applyFilter(key: string, value: string | null) {
		const url = new URL($page.url);
		if (value) {
			url.searchParams.set(key, value);
		} else {
			url.searchParams.delete(key);
		}
		url.searchParams.delete('page');
		goto(url.toString());
	}

	function handleSearch(e: Event) {
		e.preventDefault();
		applyFilter('q', search || null);
	}

	const totalPages = $derived(Math.ceil(data.total / data.pageSize));
</script>

<svelte:head>
	<title>Devices - My Collection</title>
</svelte:head>

<div class="mx-auto max-w-6xl">
	<div class="mb-6 flex items-center justify-between">
		<h1 class="text-2xl font-bold text-gray-900 dark:text-white">Devices</h1>
		<a
			href="/devices/new"
			class="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700"
		>
			Add Device
		</a>
	</div>

	<!-- Filters -->
	<div class="mb-6 flex flex-wrap items-center gap-3">
		<form onsubmit={handleSearch} class="flex-1">
			<input
				type="text"
				bind:value={search}
				placeholder="Search devices..."
				class="w-full max-w-sm rounded-md border border-gray-300 px-3 py-2 text-sm focus:border-blue-500 focus:ring-1 focus:ring-blue-500 focus:outline-none dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400"
			/>
		</form>
		<select
			onchange={(e) => applyFilter('category', (e.target as HTMLSelectElement).value || null)}
			class="rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-600 dark:bg-gray-700 dark:text-white"
		>
			<option value="">All Categories</option>
			{#each DEVICE_CATEGORIES as cat}
				<option value={cat} selected={data.filters.category === cat}>{cat}</option>
			{/each}
		</select>
		<select
			onchange={(e) => applyFilter('condition', (e.target as HTMLSelectElement).value || null)}
			class="rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-600 dark:bg-gray-700 dark:text-white"
		>
			<option value="">All Conditions</option>
			<option value="needs-repair" selected={data.filters.condition === 'needs-repair'}>Needs Repair</option>
			{#each DEVICE_CONDITIONS as cond}
				<option value={cond} selected={data.filters.condition === cond}>{cond}</option>
			{/each}
		</select>
	</div>

	<!-- Results count -->
	<p class="mb-4 text-sm text-gray-500 dark:text-gray-400">{data.total} device{data.total !== 1 ? 's' : ''}</p>

	<!-- Device Grid -->
	{#if data.devices.length === 0}
		<div class="rounded-lg border border-gray-200 bg-white p-12 text-center dark:border-gray-700 dark:bg-gray-800">
			<p class="text-gray-500 dark:text-gray-400">No devices found.</p>
			<a href="/devices/new" class="mt-2 inline-block text-sm text-blue-600 hover:text-blue-700 dark:text-blue-400">Add your first device</a>
		</div>
	{:else}
		<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
			{#each data.devices as device}
				<a
					href="/devices/{device.id}"
					class="rounded-lg border border-gray-200 bg-white transition-shadow hover:shadow-md dark:border-gray-700 dark:bg-gray-800"
				>
					<!-- Thumbnail -->
					<div class="flex h-40 items-center justify-center overflow-hidden rounded-t-lg bg-gray-100 dark:bg-gray-700">
						{#if device.thumbnail}
							<img src={device.thumbnail} alt={device.title} class="h-full w-full object-cover" />
						{:else}
							<svg class="h-12 w-12 text-gray-300 dark:text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
								<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
							</svg>
						{/if}
					</div>
					<div class="p-4">
						<h3 class="font-medium text-gray-900 dark:text-white">{device.title}</h3>
						<p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
							{[device.brand, device.model].filter(Boolean).join(' ') || device.category}
						</p>
						<div class="mt-2 flex items-center gap-2">
							<span class="rounded-full px-2 py-0.5 text-xs font-medium
								{device.condition === 'Working' ? 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300' : ''}
								{device.condition === 'In Repair' ? 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300' : ''}
								{device.condition === 'Waiting for Repair' ? 'bg-orange-100 text-orange-700 dark:bg-orange-900/40 dark:text-orange-300' : ''}
								{device.condition === 'Waiting to be Tested' ? 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300' : ''}
								{device.condition === 'Unrepairable' ? 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300' : ''}
							">
								{device.condition}
							</span>
							{#if device.year}
								<span class="text-xs text-gray-400 dark:text-gray-500">{device.year}</span>
							{/if}
						</div>
						{#if device.fullLocation}
							<p class="mt-1 text-xs text-gray-400 dark:text-gray-500">{device.fullLocation}</p>
						{/if}
					</div>
				</a>
			{/each}
		</div>
	{/if}

	<!-- Pagination -->
	{#if totalPages > 1}
		<div class="mt-6 flex items-center justify-center gap-2">
			{#if data.page > 1}
				<a
					href="?{new URLSearchParams({ ...(data.filters.category ? { category: data.filters.category } : {}), ...(data.filters.condition ? { condition: data.filters.condition } : {}), ...(data.filters.search ? { q: data.filters.search } : {}), page: String(data.page - 1) }).toString()}"
					class="rounded-md border border-gray-300 px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-100 dark:border-gray-600 dark:text-gray-400 dark:hover:bg-gray-700"
				>
					Previous
				</a>
			{/if}
			<span class="text-sm text-gray-500 dark:text-gray-400">Page {data.page} of {totalPages}</span>
			{#if data.page < totalPages}
				<a
					href="?{new URLSearchParams({ ...(data.filters.category ? { category: data.filters.category } : {}), ...(data.filters.condition ? { condition: data.filters.condition } : {}), ...(data.filters.search ? { q: data.filters.search } : {}), page: String(data.page + 1) }).toString()}"
					class="rounded-md border border-gray-300 px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-100 dark:border-gray-600 dark:text-gray-400 dark:hover:bg-gray-700"
				>
					Next
				</a>
			{/if}
		</div>
	{/if}
</div>
