<script lang="ts">
	import { onMount } from 'svelte';
	import Icon from '@iconify/svelte';
	import LiquidGlass from '$lib/components/LiquidGlass.svelte';
	import WifiSettingsLine from './WifiSettings/Line.svelte';
	import type { WiFiNetwork } from './network';

	let networks: WiFiNetwork[] = $state([]);
	let loading: boolean = $state(true);
	let selectedNetwork: WiFiNetwork | undefined = $state();

	onMount(async () => {
		loading = true;
		await fetchNetworks();
		setInterval(() => fetchNetworks(), 5000);
	});

	async function fetchNetworks() {
		try {
			const response = await fetch('http://localhost:4269/systemapi/wifi');
			networks = await response.json();
		} catch (error) {
			console.error('Failed to fetch WiFi networks:', error);
		} finally {
			loading = false;
		}
	}

	function handleNetworkSelect(network: WiFiNetwork) {
		selectedNetwork = network;
		console.log('Selected network:', network);
	}
</script>

<LiquidGlass class="rounded-xl p-6">
	<div class="flex items-center justify-between mb-4">
		<div class="flex items-center gap-3">
			<Icon icon="mdi:wifi" class="w-6 h-6 text-base-content" />
			<div>
				<h2 class="text-xl font-semibold text-base-content">WiFi Networks</h2>
				<p class="text-base-content/70 text-sm">Available wireless networks in your area</p>
			</div>
		</div>
		<button class="btn btn-ghost btn-sm" onclick={fetchNetworks} disabled={loading}>
			<Icon icon="mdi:refresh" class="w-4 h-4" />
		</button>
	</div>

	{#if loading}
		<div class="flex justify-center py-8">
			<span class="loading loading-spinner loading-md"></span>
		</div>
	{:else if networks.length === 0}
		<div class="text-center py-8 text-base-content/70">
			<Icon icon="mdi:wifi-off" class="w-12 h-12 mx-auto mb-2 opacity-50" />
			<p>No WiFi networks found</p>
		</div>
	{:else}
		<div class="space-y-2 h-64 overflow-scroll">
			{#each networks as network (network.bssid)}
				<WifiSettingsLine bind:selectedNetwork {network} onSelect={handleNetworkSelect} />
			{/each}
		</div>
	{/if}

	{#if selectedNetwork}
		<div class="mt-4 p-3 bg-base-200 rounded-lg">
			<div class="text-sm text-base-content/70">
				Selected: <span class="font-medium text-base-content">{selectedNetwork.ssid}</span>
			</div>
			<div class="text-xs text-base-content/50 mt-1">
				{selectedNetwork.bssid} • {selectedNetwork.security}
			</div>
		</div>
	{/if}
</LiquidGlass>
