<script lang="ts">
	import { get, post } from '$lib/api/client.ts';
	import type { Food, MealType, ResolveResult } from '$lib/api/types.ts';
	import { MEAL_TYPES } from '$lib/api/types.ts';

	let { date = '', defaultMeal = 'snack' as MealType, onSave = () => {}, onClose = () => {} }:
		{ date: string; defaultMeal: MealType; onSave: () => void; onClose: () => void } = $props();

	let query = $state('');
	let results = $state<Food[]>([]);
	let recentFoods = $state<Food[]>([]);
	let searching = $state(false);
	let saving = $state(false);
	let selectedFood = $state<Food | null>(null);
	let selectedServing = $state('');
	let quantity = $state(1);
	let mealType = $state<MealType>(defaultMeal);
	let mode = $state<'search' | 'quick' | 'ai'>('search');
	let quickCalories = $state(0);
	let quickName = $state('Quick add');
	let aiQuery = $state('');
	let aiResolving = $state(false);
	let aiResult = $state<ResolveResult & { snapshot_name_override?: string; note?: string } | null>(null);
	let searchTimeout: ReturnType<typeof setTimeout>;

	$effect(() => { loadRecent(); });

	async function loadRecent() {
		try { recentFoods = await get<Food[]>('/api/foods/recent?limit=15'); } catch {}
	}

	async function doSearch() {
		if (!query.trim()) { results = []; return; }
		searching = true;
		try { results = await get<Food[]>(`/api/foods/search?q=${encodeURIComponent(query)}&limit=10`); }
		catch {} finally { searching = false; }
	}

	function onInput() {
		clearTimeout(searchTimeout);
		searchTimeout = setTimeout(doSearch, 300);
	}

	function selectFood(food: Food) {
		selectedFood = food;
		const defaultServing = food.servings?.find(s => s.is_default) || food.servings?.[0];
		selectedServing = defaultServing?.id || '';
		quantity = 1;
	}

	async function aiResolve() {
		if (!aiQuery.trim()) return;
		aiResolving = true;
		aiResult = null;
		try {
			const result = await post<ResolveResult>('/api/foods/resolve', {
				raw_phrase: aiQuery,
				meal_type: mealType,
				entry_date: date,
				source: 'web',
			});
			aiResult = result;
			// If matched or AI estimated, auto-select the food
			if ((result.resolution_type === 'matched' || result.resolution_type === 'ai_estimated') && result.matched_food) {
				selectFood(result.matched_food);
				quantity = result.parsed?.quantity || 1;
			}
		} catch {} finally { aiResolving = false; }
	}

	async function save() {
		saving = true;
		try {
			if (mode === 'quick') {
				await post('/api/entries', {
					entry_type: 'quick_add',
					meal_type: mealType,
					entry_date: date,
					snapshot_food_name: quickName,
					snapshot_calories: quickCalories,
					source: 'web',
					entry_method: 'quick_add',
				});
			} else if (selectedFood) {
				const entryData: Record<string, unknown> = {
					food_id: selectedFood.id,
					meal_type: mealType,
					entry_date: date,
					quantity,
					serving_id: selectedServing || undefined,
					source: 'web',
					entry_method: mode === 'ai' ? 'ai_plate' : 'search',
					raw_text: aiQuery || undefined,
				};
				if (aiResult?.snapshot_name_override) {
					entryData.snapshot_food_name_override = aiResult.snapshot_name_override;
				}
				if (aiResult?.note) {
					entryData.note = aiResult.note;
				}
				await post('/api/entries', entryData);
			}
			onSave();
		} catch {} finally { saving = false; }
	}

	function calcNutrition(food: Food, qty: number, servingId: string) {
		const serving = food.servings?.find(s => s.id === servingId);
		const mult = serving ? qty * serving.amount_in_base : qty;
		return {
			cal: Math.round(food.calories_per_base * mult),
			pro: Math.round(food.protein_per_base * mult),
			carb: Math.round(food.carbs_per_base * mult),
			fat: Math.round(food.fat_per_base * mult),
		};
	}
</script>

<div class="modal modal-open" role="dialog">
	<div class="modal-box max-w-lg max-h-[90vh]">
		<button class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2" onclick={onClose}>X</button>
		<h3 class="font-bold text-lg mb-3">Add Food</h3>

		<!-- Meal type pills -->
		<div class="flex gap-1 mb-3">
			{#each MEAL_TYPES as mt}
				<button class="btn btn-xs" class:btn-primary={mealType === mt} onclick={() => mealType = mt}>
					{mt}
				</button>
			{/each}
		</div>

		<!-- Mode tabs -->
		<div role="tablist" class="tabs tabs-boxed mb-3">
			<button role="tab" class="tab" class:tab-active={mode === 'search'} onclick={() => { mode = 'search'; selectedFood = null; }}>Search</button>
			<button role="tab" class="tab" class:tab-active={mode === 'ai'} onclick={() => { mode = 'ai'; selectedFood = null; }}>AI Describe</button>
			<button role="tab" class="tab" class:tab-active={mode === 'quick'} onclick={() => { mode = 'quick'; selectedFood = null; }}>Quick Add</button>
		</div>

		{#if mode === 'quick'}
			<div class="flex flex-col gap-3">
				<input class="input input-bordered w-full" placeholder="Label (optional)" bind:value={quickName} />
				<input class="input input-bordered w-full" type="number" placeholder="Calories" bind:value={quickCalories} />
				<button class="btn btn-primary w-full" onclick={save} disabled={saving || quickCalories <= 0}>
					{#if saving}<span class="loading loading-spinner loading-sm"></span>{/if}
					Add {quickCalories} cal to {mealType}
				</button>
			</div>

		{:else if mode === 'ai' && !selectedFood}
			<!-- AI describe mode -->
			<div class="flex flex-col gap-3">
				<textarea
					class="textarea textarea-bordered w-full"
					rows="3"
					placeholder="Describe what you ate, e.g.&#10;2 mince tacos, no sour cream&#10;A scoop of vanilla ice cream&#10;Homemade smash burger"
					bind:value={aiQuery}
				></textarea>
				<button class="btn btn-primary w-full" onclick={aiResolve} disabled={aiResolving || !aiQuery.trim()}>
					{#if aiResolving}<span class="loading loading-spinner loading-sm"></span> Estimating...{:else}Estimate with AI{/if}
				</button>
				{#if aiResult && aiResult.resolution_type === 'queued'}
					<div class="alert alert-warning text-sm">
						<span>Could not estimate. Queued for review.</span>
					</div>
				{/if}
				{#if aiResult && aiResult.resolution_type === 'confirm' && aiResult.candidate_foods?.length}
					<div class="text-sm font-medium">Did you mean one of these?</div>
					{#each aiResult.candidate_foods as c}
						<button class="btn btn-sm btn-outline w-full justify-between" onclick={() => selectFood(c)}>
							<span>{c.name}</span>
							<span class="text-xs">{c.calories_per_base} cal/{c.base_unit}</span>
						</button>
					{/each}
				{/if}
			</div>

		{:else if selectedFood}
			<!-- Selected food detail -->
			<div class="card bg-base-200 p-3 mb-3">
				<div class="flex justify-between items-start">
					<div>
						<div class="font-semibold">{selectedFood.name}</div>
						{#if selectedFood.brand}<div class="text-xs text-base-content/50">{selectedFood.brand}</div>{/if}
						{#if selectedFood.status === 'ai_created'}<span class="badge badge-xs badge-info">AI estimated</span>{/if}
					</div>
					<button class="btn btn-ghost btn-xs" onclick={() => selectedFood = null}>Change</button>
				</div>
				<div class="flex gap-3 mt-2">
					<div class="form-control flex-1">
						<label class="label py-0"><span class="label-text text-xs">Qty</span></label>
						<input class="input input-bordered input-sm w-full" type="number" min="0.25" step="0.25" bind:value={quantity} />
					</div>
					{#if selectedFood.servings?.length > 0}
						<div class="form-control flex-[2]">
							<label class="label py-0"><span class="label-text text-xs">Serving</span></label>
							<select class="select select-bordered select-sm w-full" bind:value={selectedServing}>
								{#each selectedFood.servings as s}
									<option value={s.id}>{s.name}</option>
								{/each}
							</select>
						</div>
					{/if}
				</div>
				{#if selectedFood}
					{@const n = calcNutrition(selectedFood, quantity, selectedServing)}
					<div class="grid grid-cols-4 gap-2 mt-3 text-center text-sm">
						<div><div class="font-bold text-primary">{n.cal}</div><div class="text-xs text-base-content/50">cal</div></div>
						<div><div class="font-bold text-secondary">{n.pro}g</div><div class="text-xs text-base-content/50">protein</div></div>
						<div><div class="font-bold text-accent">{n.carb}g</div><div class="text-xs text-base-content/50">carbs</div></div>
						<div><div class="font-bold text-info">{n.fat}g</div><div class="text-xs text-base-content/50">fat</div></div>
					</div>
				{/if}
			</div>
			<button class="btn btn-primary w-full" onclick={save} disabled={saving}>
				{#if saving}<span class="loading loading-spinner loading-sm"></span>{/if}
				Add to {mealType}
			</button>

		{:else}
			<!-- Search mode -->
			<input
				class="input input-bordered w-full mb-2"
				placeholder="Search your foods..."
				bind:value={query}
				oninput={onInput}
			/>
			{#if searching}
				<div class="flex justify-center py-4"><span class="loading loading-spinner loading-md"></span></div>
			{:else}
				<div class="overflow-y-auto max-h-60">
					{#if query.trim() && results.length > 0}
						{#each results as food}
							<button class="w-full text-left px-3 py-2 hover:bg-base-200 rounded-lg flex justify-between items-center" onclick={() => selectFood(food)}>
								<div>
									<div class="text-sm font-medium">{food.name}</div>
									{#if food.brand}<span class="text-xs text-base-content/40">{food.brand}</span>{/if}
								</div>
								<div class="text-xs text-base-content/50">{food.calories_per_base} cal/{food.base_unit}</div>
							</button>
						{/each}
					{:else if query.trim()}
						<div class="text-center py-4">
							<div class="text-sm text-base-content/50 mb-2">No matches found</div>
							<button class="btn btn-sm btn-outline" onclick={() => { mode = 'ai'; aiQuery = query; }}>
								Try AI estimate for "{query}"
							</button>
						</div>
					{:else}
						{#if recentFoods.length > 0}
							<div class="text-xs text-base-content/50 mb-1">Recent</div>
						{/if}
						{#each recentFoods as food}
							<button class="w-full text-left px-3 py-2 hover:bg-base-200 rounded-lg flex justify-between items-center" onclick={() => selectFood(food)}>
								<div>
									<div class="text-sm font-medium">{food.name}</div>
									<div class="text-xs text-base-content/50">{food.calories_per_base} cal/{food.base_unit}</div>
								</div>
							</button>
						{/each}
						{#if recentFoods.length === 0}
							<div class="text-center text-sm text-base-content/50 py-4">No foods yet. Use AI Describe to add your first food.</div>
						{/if}
					{/if}
				</div>
			{/if}
		{/if}
	</div>
	<form method="dialog" class="modal-backdrop"><button onclick={onClose}>close</button></form>
</div>
