<script lang="ts">
	import { get, put } from '$lib/api/client.ts';
	import type { Goal, User } from '$lib/api/types.ts';
	import { today } from '$lib/api/client.ts';

	let users = $state<User[]>([]);
	let selectedUser = $state('');
	let goals = $state<Goal[]>([]);
	let loading = $state(true);

	let calories = $state(2000);
	let protein = $state(150);
	let carbs = $state(200);
	let fat = $state(65);
	let startDate = $state(today());
	let saving = $state(false);

	$effect(() => { loadUsers(); });
	$effect(() => { if (selectedUser) loadGoals(); });

	async function loadUsers() {
		users = await get<User[]>('/api/users');
		const me = await get<User>('/api/user');
		selectedUser = me.id;
	}

	async function loadGoals() {
		loading = true;
		try {
			goals = await get<Goal[]>(`/api/goals?user_id=${selectedUser}`);
			const current = goals.find(g => g.is_active);
			if (current) {
				calories = current.calories; protein = current.protein;
				carbs = current.carbs; fat = current.fat;
			}
		} catch {} finally { loading = false; }
	}

	async function saveGoal() {
		saving = true;
		try {
			await put('/api/goals', { user_id: selectedUser, start_date: startDate, calories, protein, carbs, fat });
			loadGoals();
		} catch {} finally { saving = false; }
	}

	function userName(id: string) { return users.find(u => u.id === id)?.display_name || ''; }
</script>

<div class="max-w-2xl mx-auto px-4 py-6">
	<div class="flex items-center justify-between mb-6">
		<div>
			<h1 class="text-3xl font-bold">Goals</h1>
			<p class="text-base-content/50 text-sm mt-0.5">Daily nutrition targets</p>
		</div>
		<select class="select select-bordered select-sm" bind:value={selectedUser}>
			{#each users as u}
				<option value={u.id}>{u.display_name}</option>
			{/each}
		</select>
	</div>

	{#if loading}
		<div class="flex justify-center py-12"><span class="loading loading-spinner loading-lg text-primary"></span></div>
	{:else}
		<!-- Set goals card -->
		<div class="rounded-xl border border-primary/20 bg-gradient-to-br from-primary/10 to-primary/5 p-6 mb-8 shadow-md">
			<div class="flex items-center gap-3 mb-4">
				<div class="p-2 rounded-xl bg-primary/15">
					<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-primary" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M6 2a1 1 0 00-1 1v1H4a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V6a2 2 0 00-2-2h-1V3a1 1 0 10-2 0v1H7V3a1 1 0 00-1-1zm0 5a1 1 0 000 2h8a1 1 0 100-2H6z" clip-rule="evenodd"/></svg>
				</div>
				<h2 class="font-bold text-lg">Set Goals for {userName(selectedUser)}</h2>
			</div>
			<div class="flex flex-col gap-3">
				<div>
					<div class="text-xs text-base-content/50 font-medium uppercase tracking-wide mb-1">Start Date</div>
					<input type="date" class="input input-bordered input-sm w-full max-w-xs" bind:value={startDate} />
				</div>
				<div class="grid grid-cols-2 gap-3">
					<div>
						<div class="text-xs text-base-content/50 font-medium uppercase tracking-wide mb-1">Calories</div>
						<input type="number" class="input input-bordered w-full" bind:value={calories} />
					</div>
					<div>
						<div class="text-xs text-base-content/50 font-medium uppercase tracking-wide mb-1">Protein (g)</div>
						<input type="number" class="input input-bordered w-full" bind:value={protein} />
					</div>
					<div>
						<div class="text-xs text-base-content/50 font-medium uppercase tracking-wide mb-1">Carbs (g)</div>
						<input type="number" class="input input-bordered w-full" bind:value={carbs} />
					</div>
					<div>
						<div class="text-xs text-base-content/50 font-medium uppercase tracking-wide mb-1">Fat (g)</div>
						<input type="number" class="input input-bordered w-full" bind:value={fat} />
					</div>
				</div>
				<button class="btn btn-primary gap-2 mt-1" onclick={saveGoal} disabled={saving}>
					{#if saving}<span class="loading loading-spinner loading-sm"></span>{/if}
					Save Goals
				</button>
			</div>
		</div>

		<!-- Goal history -->
		{#if goals.length > 0}
			<div class="flex items-center gap-2 mb-4">
				<div class="w-2 h-2 rounded-full bg-info"></div>
				<h2 class="text-xl font-bold">History</h2>
			</div>
			<div class="space-y-2">
				{#each goals as g}
					<div class="rounded-xl border p-4 shadow-sm card-hover {g.is_active ? 'border-primary/30 bg-gradient-to-br from-primary/5 to-transparent' : 'border-base-300 bg-base-200/50'}">
						<div class="flex justify-between items-center">
							<div>
								<div class="text-sm font-medium">
									{g.start_date}{g.end_date ? ` — ${g.end_date}` : ''}
								</div>
								<div class="flex gap-3 text-xs text-base-content/50 mt-1">
									<span>{g.calories} cal</span>
									<span>{g.protein}g P</span>
									<span>{g.carbs}g C</span>
									<span>{g.fat}g F</span>
								</div>
							</div>
							{#if g.is_active}
								<span class="badge badge-primary badge-sm">Active</span>
							{:else}
								<span class="badge badge-ghost badge-sm">Ended</span>
							{/if}
						</div>
					</div>
				{/each}
			</div>
		{/if}
	{/if}
</div>
