<script lang="ts">
	import { onMount } from 'svelte';
	import { PUBLIC_API_URL } from '$env/static/public';

	const API_BASE = (PUBLIC_API_URL || 'http://localhost:8000') + '/api/v1';

	let activeTab: 'dashboard' | 'log' | 'compare' | 'alerts' = 'dashboard';
	let loading = false;
	let error = '';

	// Dashboard data
	let stats: any = null;
	let summary: any = null;
	let providers: any[] = [];

	// Log form
	let logProvider = 'openai';
	let logModel = '';
	let logAmount = '';
	let logInputTokens = '';
	let logOutputTokens = '';
	let logProject = 'default';
	let logDescription = '';
	let logDate = new Date().toISOString().split('T')[0];
	let logSuccess = '';

	// Compare
	let compareInputTokens = 1000000;
	let compareOutputTokens = 500000;
	let compareResults: any = null;

	// Alerts
	let alerts: any[] = [];
	let alertName = '';
	let alertProvider = '';
	let alertProject = '';
	let alertLimit = '';
	let alertThreshold = 0.8;

	onMount(async () => {
		await Promise.all([loadStats(), loadSummary(), loadProviders(), loadAlerts()]);
	});

	async function loadStats() {
		try {
			const response = await fetch(`${API_BASE}/costs/stats`);
			if (response.ok) {
				stats = await response.json();
			}
		} catch (e) {
			console.error('Failed to load stats:', e);
		}
	}

	async function loadSummary() {
		try {
			const response = await fetch(`${API_BASE}/costs/summary`);
			if (response.ok) {
				summary = await response.json();
			}
		} catch (e) {
			console.error('Failed to load summary:', e);
		}
	}

	async function loadProviders() {
		try {
			const response = await fetch(`${API_BASE}/costs/providers`);
			if (response.ok) {
				const data = await response.json();
				providers = data.providers || [];
			}
		} catch (e) {
			console.error('Failed to load providers:', e);
		}
	}

	async function loadAlerts() {
		try {
			const response = await fetch(`${API_BASE}/costs/alerts`);
			if (response.ok) {
				const data = await response.json();
				alerts = data.alerts || [];
			}
		} catch (e) {
			console.error('Failed to load alerts:', e);
		}
	}

	async function logCost() {
		if (!logAmount) {
			error = 'Please enter an amount';
			return;
		}

		loading = true;
		error = '';
		logSuccess = '';

		try {
			const response = await fetch(`${API_BASE}/costs/log`, {
				method: 'POST',
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify({
					provider: logProvider,
					model: logModel || null,
					amount: parseFloat(logAmount),
					input_tokens: logInputTokens ? parseInt(logInputTokens) : null,
					output_tokens: logOutputTokens ? parseInt(logOutputTokens) : null,
					project: logProject,
					description: logDescription || null,
					entry_date: logDate
				})
			});

			if (!response.ok) {
				const errData = await response.json();
				throw new Error(errData.detail || 'Failed to log cost');
			}

			const result = await response.json();
			logSuccess = `Cost logged: $${logAmount} for ${logProvider}`;

			// Reset form
			logAmount = '';
			logInputTokens = '';
			logOutputTokens = '';
			logDescription = '';

			// Reload data
			await Promise.all([loadStats(), loadSummary()]);
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to log cost';
		} finally {
			loading = false;
		}
	}

	async function compareCosts() {
		loading = true;
		error = '';

		try {
			const response = await fetch(
				`${API_BASE}/costs/compare-providers?input_tokens=${compareInputTokens}&output_tokens=${compareOutputTokens}`
			);

			if (!response.ok) {
				throw new Error('Failed to compare costs');
			}

			compareResults = await response.json();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to compare costs';
		} finally {
			loading = false;
		}
	}

	async function createAlert() {
		if (!alertName || !alertLimit) {
			error = 'Please enter alert name and limit';
			return;
		}

		loading = true;
		error = '';

		try {
			const response = await fetch(`${API_BASE}/costs/alerts`, {
				method: 'POST',
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify({
					name: alertName,
					provider: alertProvider || null,
					project: alertProject || null,
					monthly_limit: parseFloat(alertLimit),
					alert_threshold: alertThreshold
				})
			});

			if (!response.ok) {
				throw new Error('Failed to create alert');
			}

			// Reset form
			alertName = '';
			alertProvider = '';
			alertProject = '';
			alertLimit = '';

			await loadAlerts();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to create alert';
		} finally {
			loading = false;
		}
	}

	async function deleteAlert(alertId: string) {
		try {
			await fetch(`${API_BASE}/costs/alerts/${alertId}`, {
				method: 'DELETE'
			});
			await loadAlerts();
		} catch (e) {
			console.error('Failed to delete alert:', e);
		}
	}

	function getStatusColor(status: string): string {
		switch (status) {
			case 'exceeded':
				return 'bg-red-100 text-red-700 border-red-200';
			case 'warning':
				return 'bg-orange-100 text-orange-700 border-orange-200';
			default:
				return 'bg-green-100 text-green-700 border-green-200';
		}
	}

	function formatCurrency(amount: number): string {
		return new Intl.NumberFormat('en-US', {
			style: 'currency',
			currency: 'USD',
			minimumFractionDigits: 2
		}).format(amount);
	}

	function getModelsForProvider(providerName: string): string[] {
		const provider = providers.find((p) => p.name === providerName);
		return provider ? provider.models.map((m: any) => m.name) : [];
	}

	$: availableModels = getModelsForProvider(logProvider);
</script>

<div class="max-w-6xl mx-auto animate-fade-in">
	<!-- Header -->
	<div class="mb-6">
		<h1 class="text-2xl font-bold text-surface-800">Vendor Cost Tracker</h1>
		<p class="text-surface-600 mt-1">Track, analyze, and optimize your AI API spending across providers</p>
	</div>

	<!-- Tabs -->
	<div class="flex gap-1 mb-6 border-b border-surface-200">
		<button
			class="px-4 py-2 text-sm font-medium transition-colors {activeTab === 'dashboard'
				? 'text-primary-600 border-b-2 border-primary-600'
				: 'text-surface-500 hover:text-surface-700'}"
			on:click={() => (activeTab = 'dashboard')}
		>
			Dashboard
		</button>
		<button
			class="px-4 py-2 text-sm font-medium transition-colors {activeTab === 'log'
				? 'text-primary-600 border-b-2 border-primary-600'
				: 'text-surface-500 hover:text-surface-700'}"
			on:click={() => (activeTab = 'log')}
		>
			Log Cost
		</button>
		<button
			class="px-4 py-2 text-sm font-medium transition-colors {activeTab === 'compare'
				? 'text-primary-600 border-b-2 border-primary-600'
				: 'text-surface-500 hover:text-surface-700'}"
			on:click={() => (activeTab = 'compare')}
		>
			Compare Providers
		</button>
		<button
			class="px-4 py-2 text-sm font-medium transition-colors {activeTab === 'alerts'
				? 'text-primary-600 border-b-2 border-primary-600'
				: 'text-surface-500 hover:text-surface-700'}"
			on:click={() => (activeTab = 'alerts')}
		>
			Budget Alerts
		</button>
	</div>

	{#if error}
		<div class="mb-4 p-3 bg-red-50 text-red-700 rounded-lg border border-red-200">
			{error}
		</div>
	{/if}

	<!-- Dashboard Tab -->
	{#if activeTab === 'dashboard'}
		<div class="grid grid-cols-1 lg:grid-cols-3 gap-4">
			<!-- Stats Cards -->
			<div class="lg:col-span-3 grid grid-cols-4 gap-3">
				<div class="card p-4 text-center">
					<p class="text-xs text-surface-600">This Month</p>
					<p class="text-xl font-bold text-primary-600">
						{stats?.this_month_total ? formatCurrency(stats.this_month_total) : '$0.00'}
					</p>
				</div>
				<div class="card p-4 text-center">
					<p class="text-xs text-surface-600">Last Month</p>
					<p class="text-xl font-bold text-surface-700">
						{stats?.last_month_total ? formatCurrency(stats.last_month_total) : '$0.00'}
					</p>
				</div>
				<div class="card p-4 text-center">
					<p class="text-xs text-surface-600">Change</p>
					<p class="text-xl font-bold {stats?.month_over_month_change >= 0 ? 'text-red-600' : 'text-green-600'}">
						{stats?.month_over_month_change !== undefined ? `${stats.month_over_month_change > 0 ? '+' : ''}${stats.month_over_month_change}%` : '0%'}
					</p>
				</div>
				<div class="card p-4 text-center">
					<p class="text-xs text-surface-600">All Time</p>
					<p class="text-xl font-bold text-surface-800">
						{stats?.all_time_total ? formatCurrency(stats.all_time_total) : '$0.00'}
					</p>
				</div>
			</div>

			<!-- By Provider -->
			<div class="card p-4">
				<h3 class="text-sm font-bold text-surface-800 mb-3">By Provider</h3>
				{#if summary?.by_provider && Object.keys(summary.by_provider).length > 0}
					<div class="space-y-2">
						{#each Object.entries(summary.by_provider) as [provider, amount]}
							<div class="flex items-center justify-between p-2 bg-surface-50 rounded-lg">
								<span class="text-sm font-medium capitalize">{provider}</span>
								<span class="text-sm font-bold text-primary-600">{formatCurrency(Number(amount))}</span>
							</div>
						{/each}
					</div>
				{:else}
					<p class="text-sm text-surface-500 text-center py-4">No data yet</p>
				{/if}
			</div>

			<!-- By Project -->
			<div class="card p-4">
				<h3 class="text-sm font-bold text-surface-800 mb-3">By Project</h3>
				{#if summary?.by_project && Object.keys(summary.by_project).length > 0}
					<div class="space-y-2">
						{#each Object.entries(summary.by_project) as [project, amount]}
							<div class="flex items-center justify-between p-2 bg-surface-50 rounded-lg">
								<span class="text-sm font-medium">{project}</span>
								<span class="text-sm font-bold text-primary-600">{formatCurrency(Number(amount))}</span>
							</div>
						{/each}
					</div>
				{:else}
					<p class="text-sm text-surface-500 text-center py-4">No data yet</p>
				{/if}
			</div>

			<!-- By Model -->
			<div class="card p-4">
				<h3 class="text-sm font-bold text-surface-800 mb-3">By Model</h3>
				{#if summary?.by_model && Object.keys(summary.by_model).length > 0}
					<div class="space-y-2 max-h-[200px] overflow-y-auto">
						{#each Object.entries(summary.by_model).slice(0, 10) as [model, amount]}
							<div class="flex items-center justify-between p-2 bg-surface-50 rounded-lg">
								<span class="text-xs font-medium truncate flex-1">{model}</span>
								<span class="text-sm font-bold text-primary-600 ml-2">{formatCurrency(Number(amount))}</span>
							</div>
						{/each}
					</div>
				{:else}
					<p class="text-sm text-surface-500 text-center py-4">No data yet</p>
				{/if}
			</div>

			<!-- Daily Breakdown -->
			<div class="lg:col-span-3 card p-4">
				<h3 class="text-sm font-bold text-surface-800 mb-3">Daily Breakdown</h3>
				{#if summary?.daily_breakdown && summary.daily_breakdown.length > 0}
					<div class="overflow-x-auto">
						<div class="flex gap-1 min-w-fit">
							{#each summary.daily_breakdown.slice(-14) as day}
								<div class="flex flex-col items-center">
									<div
										class="w-8 bg-primary-200 rounded-t"
										style="height: {Math.max(20, (day.amount / Math.max(...summary.daily_breakdown.map(d => d.amount))) * 100)}px"
									></div>
									<span class="text-[10px] text-surface-500 mt-1">{day.date.slice(-2)}</span>
								</div>
							{/each}
						</div>
					</div>
				{:else}
					<p class="text-sm text-surface-500 text-center py-8">No daily data yet. Start logging costs!</p>
				{/if}
			</div>
		</div>

	<!-- Log Cost Tab -->
	{:else if activeTab === 'log'}
		<div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
			<div class="card p-4">
				<h3 class="text-base font-bold text-surface-800 mb-4">Log New Cost Entry</h3>

				<div class="space-y-4">
					<div class="grid grid-cols-2 gap-3">
						<div>
							<label class="label">Provider</label>
							<select bind:value={logProvider} class="input">
								{#each providers as provider}
									<option value={provider.name}>{provider.name}</option>
								{/each}
							</select>
						</div>
						<div>
							<label class="label">Model</label>
							<select bind:value={logModel} class="input">
								<option value="">Select model...</option>
								{#each availableModels as model}
									<option value={model}>{model}</option>
								{/each}
							</select>
						</div>
					</div>

					<div class="grid grid-cols-2 gap-3">
						<div>
							<label class="label">Amount ($)</label>
							<input
								type="number"
								step="0.01"
								bind:value={logAmount}
								placeholder="0.00"
								class="input"
							/>
						</div>
						<div>
							<label class="label">Date</label>
							<input type="date" bind:value={logDate} class="input" />
						</div>
					</div>

					<div class="grid grid-cols-2 gap-3">
						<div>
							<label class="label">Input Tokens</label>
							<input
								type="number"
								bind:value={logInputTokens}
								placeholder="Optional"
								class="input"
							/>
						</div>
						<div>
							<label class="label">Output Tokens</label>
							<input
								type="number"
								bind:value={logOutputTokens}
								placeholder="Optional"
								class="input"
							/>
						</div>
					</div>

					<div>
						<label class="label">Project</label>
						<input
							type="text"
							bind:value={logProject}
							placeholder="default"
							class="input"
						/>
					</div>

					<div>
						<label class="label">Description</label>
						<input
							type="text"
							bind:value={logDescription}
							placeholder="Optional description"
							class="input"
						/>
					</div>

					<button
						on:click={logCost}
						disabled={loading || !logAmount}
						class="btn-primary w-full disabled:opacity-50"
					>
						{loading ? 'Logging...' : 'Log Cost'}
					</button>

					{#if logSuccess}
						<div class="p-3 bg-green-50 text-green-700 rounded-lg border border-green-200">
							{logSuccess}
						</div>
					{/if}
				</div>
			</div>

			<!-- Pricing Reference -->
			<div class="card p-4">
				<h3 class="text-base font-bold text-surface-800 mb-4">Pricing Reference</h3>
				<div class="space-y-3 max-h-[500px] overflow-y-auto">
					{#each providers as provider}
						<div class="bg-surface-50 rounded-lg p-3 border border-surface-100">
							<h4 class="text-sm font-semibold text-surface-700 capitalize mb-2">{provider.name}</h4>
							<div class="space-y-1">
								{#each provider.models.slice(0, 5) as model}
									<div class="flex justify-between text-xs">
										<span class="text-surface-600">{model.name}</span>
										<span class="text-surface-800 font-mono">
											${model.input_price}/{model.output_price}
										</span>
									</div>
								{/each}
							</div>
						</div>
					{/each}
				</div>
				<p class="text-xs text-surface-500 mt-2">Prices per 1M tokens (input/output)</p>
			</div>
		</div>

	<!-- Compare Tab -->
	{:else if activeTab === 'compare'}
		<div class="grid grid-cols-1 lg:grid-cols-3 gap-4">
			<div class="card p-4">
				<h3 class="text-base font-bold text-surface-800 mb-4">Compare Provider Costs</h3>

				<div class="space-y-4">
					<div>
						<label class="label">Input Tokens</label>
						<input
							type="number"
							bind:value={compareInputTokens}
							class="input"
						/>
					</div>

					<div>
						<label class="label">Output Tokens</label>
						<input
							type="number"
							bind:value={compareOutputTokens}
							class="input"
						/>
					</div>

					<button
						on:click={compareCosts}
						disabled={loading}
						class="btn-primary w-full disabled:opacity-50"
					>
						{loading ? 'Comparing...' : 'Compare Costs'}
					</button>
				</div>

				{#if compareResults}
					<div class="mt-4 space-y-2">
						<div class="p-3 bg-green-50 rounded-lg border border-green-200">
							<p class="text-xs text-green-600">Cheapest Option</p>
							<p class="text-sm font-bold text-green-700">
								{compareResults.cheapest?.provider} / {compareResults.cheapest?.model}
							</p>
							<p class="text-lg font-bold text-green-800">
								{formatCurrency(compareResults.cheapest?.total_cost || 0)}
							</p>
						</div>

						<div class="p-3 bg-red-50 rounded-lg border border-red-200">
							<p class="text-xs text-red-600">Most Expensive</p>
							<p class="text-sm font-bold text-red-700">
								{compareResults.most_expensive?.provider} / {compareResults.most_expensive?.model}
							</p>
							<p class="text-lg font-bold text-red-800">
								{formatCurrency(compareResults.most_expensive?.total_cost || 0)}
							</p>
						</div>

						<div class="p-3 bg-blue-50 rounded-lg border border-blue-200">
							<p class="text-xs text-blue-600">Potential Savings</p>
							<p class="text-lg font-bold text-blue-800">
								{formatCurrency(compareResults.savings_potential || 0)}
							</p>
						</div>
					</div>
				{/if}
			</div>

			<div class="lg:col-span-2 card p-4">
				<h3 class="text-base font-bold text-surface-800 mb-4">All Providers</h3>

				{#if compareResults?.comparisons}
					<div class="overflow-x-auto">
						<table class="table-modern">
							<thead>
								<tr>
									<th>Provider</th>
									<th>Model</th>
									<th class="text-right">Input Cost</th>
									<th class="text-right">Output Cost</th>
									<th class="text-right">Total</th>
								</tr>
							</thead>
							<tbody>
								{#each compareResults.comparisons as comp, i}
									<tr class="{i === 0 ? 'bg-green-50' : i === compareResults.comparisons.length - 1 ? 'bg-red-50' : ''}">
										<td class="capitalize">{comp.provider}</td>
										<td class="text-sm">{comp.model}</td>
										<td class="text-right font-mono text-sm">{formatCurrency(comp.input_cost)}</td>
										<td class="text-right font-mono text-sm">{formatCurrency(comp.output_cost)}</td>
										<td class="text-right font-mono text-sm font-bold">{formatCurrency(comp.total_cost)}</td>
									</tr>
								{/each}
							</tbody>
						</table>
					</div>
				{:else}
					<div class="text-center py-12 text-surface-500">
						Enter token counts and click Compare to see pricing across all providers
					</div>
				{/if}
			</div>
		</div>

	<!-- Alerts Tab -->
	{:else if activeTab === 'alerts'}
		<div class="grid grid-cols-1 lg:grid-cols-3 gap-4">
			<div class="card p-4">
				<h3 class="text-base font-bold text-surface-800 mb-4">Create Budget Alert</h3>

				<div class="space-y-4">
					<div>
						<label class="label">Alert Name</label>
						<input
							type="text"
							bind:value={alertName}
							placeholder="e.g., Monthly OpenAI Budget"
							class="input"
						/>
					</div>

					<div>
						<label class="label">Provider (optional)</label>
						<select bind:value={alertProvider} class="input">
							<option value="">All providers</option>
							{#each providers as provider}
								<option value={provider.name}>{provider.name}</option>
							{/each}
						</select>
					</div>

					<div>
						<label class="label">Project (optional)</label>
						<input
							type="text"
							bind:value={alertProject}
							placeholder="Leave empty for all projects"
							class="input"
						/>
					</div>

					<div>
						<label class="label">Monthly Limit ($)</label>
						<input
							type="number"
							step="0.01"
							bind:value={alertLimit}
							placeholder="1000.00"
							class="input"
						/>
					</div>

					<div>
						<label class="label">Alert at {alertThreshold * 100}% of limit</label>
						<input
							type="range"
							min="0.5"
							max="1"
							step="0.05"
							bind:value={alertThreshold}
							class="w-full"
						/>
					</div>

					<button
						on:click={createAlert}
						disabled={loading || !alertName || !alertLimit}
						class="btn-primary w-full disabled:opacity-50"
					>
						{loading ? 'Creating...' : 'Create Alert'}
					</button>
				</div>
			</div>

			<div class="lg:col-span-2 card p-4">
				<h3 class="text-base font-bold text-surface-800 mb-4">Active Alerts</h3>

				{#if alerts.length > 0}
					<div class="space-y-3">
						{#each alerts as alert}
							<div class="p-4 rounded-lg border {getStatusColor(alert.status)}">
								<div class="flex items-start justify-between">
									<div>
										<h4 class="font-semibold">{alert.name}</h4>
										<p class="text-xs opacity-80 mt-1">
											{alert.provider ? `Provider: ${alert.provider}` : 'All providers'}
											{alert.project ? ` | Project: ${alert.project}` : ''}
										</p>
									</div>
									<button
										on:click={() => deleteAlert(alert.id)}
										class="text-xs opacity-60 hover:opacity-100"
									>
										Delete
									</button>
								</div>

								<div class="mt-3">
									<div class="flex justify-between text-sm mb-1">
										<span>{formatCurrency(alert.current_spend)} spent</span>
										<span>{formatCurrency(alert.monthly_limit)} limit</span>
									</div>
									<div class="w-full bg-white/50 rounded-full h-2">
										<div
											class="h-2 rounded-full transition-all {alert.percent_used >= 100
												? 'bg-red-500'
												: alert.percent_used >= 80
													? 'bg-orange-500'
													: 'bg-green-500'}"
											style="width: {Math.min(100, alert.percent_used)}%"
										></div>
									</div>
									<p class="text-xs mt-1 opacity-80">
										{alert.percent_used.toFixed(1)}% used | {formatCurrency(alert.remaining)} remaining
									</p>
								</div>
							</div>
						{/each}
					</div>
				{:else}
					<div class="text-center py-12 text-surface-500">
						No budget alerts configured. Create one to monitor your spending!
					</div>
				{/if}
			</div>
		</div>
	{/if}
</div>
