<script lang="ts">
	import { currentUser } from '$lib/stores/user';
	import { api } from '$lib/api/client';
	import { t } from '$lib/i18n';

	interface FavoriteLocation {
		id: number;
		name: string;
		latitude: number;
		longitude: number;
	}

	let locations: FavoriteLocation[] = [];
	let loading = true;
	let error = '';
	let addingNew = false;
	let editingId: number | null = null;

	let newName = '';
	let newLat = 0;
	let newLng = 0;

	$: if ($currentUser) {
		loadLocations();
	}

	async function loadLocations() {
		if (!$currentUser) return;
		loading = true;
		error = '';

		try {
			const userData = await api.getMe();
			// Assuming favorite locations are part of user data
			// The API might need to be extended if not available
			locations = (userData as any).favoriteLocations || [];
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to load locations';
		} finally {
			loading = false;
		}
	}

	function startAdd() {
		addingNew = true;
		newName = '';
		newLat = 0;
		newLng = 0;
		error = '';
	}

	function cancelAdd() {
		addingNew = false;
		editingId = null;
	}

	async function saveLocation() {
		if (!newName.trim()) return;

		error = '';
		try {
			if (editingId) {
				await api.updateFavoriteLocation(editingId, {
					name: newName.trim(),
					latitude: newLat,
					longitude: newLng
				});
			} else {
				await api.addFavoriteLocation({
					name: newName.trim(),
					latitude: newLat,
					longitude: newLng
				});
			}
			await loadLocations();
			addingNew = false;
			editingId = null;
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to save location';
		}
	}

	function editLocation(location: FavoriteLocation) {
		editingId = location.id;
		addingNew = true;
		newName = location.name;
		newLat = location.latitude;
		newLng = location.longitude;
	}

	function goToLocation(lat: number, lng: number) {
		// This would need to communicate with the map component
		// For now, just show coordinates
		console.log('Navigate to:', lat, lng);
	}
</script>

<div class="card bg-base-100 shadow-xl">
	<div class="card-body">
		<h2 class="card-title">Favorite Locations</h2>

		{#if loading}
			<div class="flex justify-center py-8">
				<span class="loading loading-spinner loading-lg"></span>
			</div>
		{:else if error && !addingNew}
			<div class="alert alert-error">
				<span>{error}</span>
			</div>
		{:else}
			<div class="space-y-2">
				{#each locations as location (location.id)}
					<div class="flex items-center justify-between p-3 rounded-box bg-base-200 hover:bg-base-300 transition">
						<div class="flex-1">
							<p class="font-medium">{location.name}</p>
							<p class="text-xs text-base-content/60">
								{location.latitude.toFixed(4)}, {location.longitude.toFixed(4)}
							</p>
						</div>
						<div class="flex gap-2">
							<button
								class="btn btn-ghost btn-xs"
								on:click={() => goToLocation(location.latitude, location.longitude)}
							>
								Go
							</button>
							<button class="btn btn-ghost btn-xs" on:click={() => editLocation(location)}>
								Edit
							</button>
						</div>
					</div>
				{:else}
					<p class="text-sm text-base-content/60 py-4 text-center">
						No favorite locations yet. Add one to save your favorite spots!
					</p>
				{/each}
			</div>

			{#if addingNew}
				<div class="divider"></div>
				<div class="space-y-3">
					<div class="form-control">
						<label class="label" for="loc-name">
							<span class="label-text">Location Name</span>
						</label>
						<input
							id="loc-name"
							type="text"
							class="input input-bordered input-sm"
							bind:value={newName}
							placeholder="My favorite spot"
							maxlength="50"
						/>
					</div>

					<div class="grid grid-cols-2 gap-2">
						<div class="form-control">
							<label class="label" for="loc-lat">
								<span class="label-text text-xs">Latitude</span>
							</label>
							<input
								id="loc-lat"
								type="number"
								class="input input-bordered input-sm"
								bind:value={newLat}
								step="0.0001"
								min="-90"
								max="90"
							/>
						</div>
						<div class="form-control">
							<label class="label" for="loc-lng">
								<span class="label-text text-xs">Longitude</span>
							</label>
							<input
								id="loc-lng"
								type="number"
								class="input input-bordered input-sm"
								bind:value={newLng}
								step="0.0001"
								min="-180"
								max="180"
							/>
						</div>
					</div>

					{#if error}
						<div class="alert alert-error alert-sm">
							<span class="text-xs">{error}</span>
						</div>
					{/if}

					<div class="flex gap-2 justify-end">
						<button class="btn btn-ghost btn-sm" on:click={cancelAdd}>
							{$t('cancel')}
						</button>
						<button class="btn btn-primary btn-sm" on:click={saveLocation} disabled={!newName.trim()}>
							{$t('save')}
						</button>
					</div>
				</div>
			{:else}
				<button class="btn btn-primary btn-sm btn-block mt-4" on:click={startAdd}>
					Add Location
				</button>
			{/if}
		{/if}
	</div>
</div>
