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

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

	let model = 'gpt-4o';
	let inputTokens = 500;
	let outputTokens = 500;
	let requestsPerDay = 1000;
	let daysPerMonth = 30;

	let result: any = null;
	let loading = false;
	let error = '';

	// Pricing metadata
	let pricingInfo: any = null;
	let models: any[] = [];
	let showPricingPanel = false;

	// Override form
	let overrideModel = '';
	let overrideInput = 0;
	let overrideOutput = 0;
	let overrideDescription = '';
	let overrideLoading = false;

	onMount(async () => {
		await loadPricingInfo();
	});

	async function loadPricingInfo() {
		try {
			pricingInfo = await api.estimate.models();
			models = pricingInfo.models || [];
		} catch (e) {
			console.error('Failed to load pricing info', e);
		}
	}

	async function calculate() {
		loading = true;
		error = '';
		try {
			result = await api.estimate.calculate({
				model,
				input_tokens_per_request: inputTokens,
				output_tokens_per_request: outputTokens,
				requests_per_day: requestsPerDay,
				days_per_month: daysPerMonth
			});
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to calculate';
		} finally {
			loading = false;
		}
	}

	async function saveOverride() {
		if (!overrideModel || overrideInput <= 0 || overrideOutput <= 0) {
			alert('Please fill in all fields');
			return;
		}
		overrideLoading = true;
		try {
			const response = await fetch(`${API_BASE}/estimate/pricing/override`, {
				method: 'POST',
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify({
					model: overrideModel,
					input: overrideInput,
					output: overrideOutput,
					description: overrideDescription || `Custom price for ${overrideModel}`
				})
			});
			if (response.ok) {
				await loadPricingInfo();
				overrideModel = '';
				overrideInput = 0;
				overrideOutput = 0;
				overrideDescription = '';
				alert('Price override saved!');
			}
		} catch (e) {
			alert('Failed to save override');
		} finally {
			overrideLoading = false;
		}
	}

	function selectModelForOverride(m: any) {
		overrideModel = m.name;
		overrideInput = m.input;
		overrideOutput = m.output;
		overrideDescription = '';
	}

	async function deleteOverride(modelName: string) {
		if (!confirm(`Delete override for ${modelName}?`)) return;
		try {
			const response = await fetch(`${API_BASE}/estimate/pricing/override/${encodeURIComponent(modelName)}`, {
				method: 'DELETE'
			});
			if (response.ok) {
				await loadPricingInfo();
			} else {
				alert('Failed to delete override');
			}
		} catch (e) {
			alert('Failed to delete override');
		}
	}

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

	function formatNumber(value: number): string {
		return new Intl.NumberFormat('en-US').format(value);
	}

	function getProviderBadgeClass(provider: string): string {
		switch (provider) {
			case 'openai': return 'badge-openai';
			case 'anthropic': return 'badge-anthropic';
			case 'google': return 'badge-google';
			case 'custom': return 'badge-custom';
			default: return 'bg-surface-100 text-surface-600';
		}
	}
</script>

<div class="max-w-6xl mx-auto animate-fade-in">
	<!-- Pricing Info Banner -->
	{#if pricingInfo}
		<div class="card p-3 mb-4">
			<div class="flex items-center justify-between flex-wrap gap-4">
				<div class="flex items-center gap-6">
					<div class="flex items-center gap-2">
						<div class="w-2 h-2 rounded-full bg-green-500 animate-pulse"></div>
						<span class="text-sm text-surface-600">
							<span class="font-semibold">{models.length}</span> models available
						</span>
					</div>
					<div class="text-sm text-surface-400">
						Last updated: <span class="text-surface-600 font-medium">{pricingInfo.last_updated}</span>
					</div>
				</div>
				<div class="flex items-center gap-3">
					<button
						on:click={() => (showPricingPanel = !showPricingPanel)}
						class="btn-secondary text-sm"
					>
						{showPricingPanel ? 'Hide Pricing' : 'View/Edit Pricing'}
					</button>
					{#if pricingInfo.sources}
						{#each Object.entries(pricingInfo.sources) as [provider, url]}
							<a
								href={String(url)}
								target="_blank"
								rel="noopener"
								class="text-xs px-3 py-1.5 rounded-lg bg-surface-100 text-surface-500 hover:bg-surface-200 hover:text-surface-700 transition-colors font-medium"
							>
								{provider}
							</a>
						{/each}
					{/if}
				</div>
			</div>
		</div>
	{/if}

	<!-- Pricing Panel (Collapsible) -->
	{#if showPricingPanel}
		<div class="card p-6 mb-6 animate-fade-in">
			<h2 class="section-header">Model Pricing <span class="text-surface-400 font-normal text-sm">(per 1M tokens)</span></h2>

			<div class="grid grid-cols-1 lg:grid-cols-5 gap-6">
				<!-- Pricing Table -->
				<div class="lg:col-span-3">
					<div class="overflow-x-auto rounded-xl border border-surface-100">
						<table class="table-modern">
							<thead>
								<tr>
									<th>Model</th>
									<th>Provider</th>
									<th class="text-right">Input</th>
									<th class="text-right">Output</th>
									<th class="text-center">Actions</th>
								</tr>
							</thead>
							<tbody>
								{#each models as m}
									<tr>
										<td class="font-semibold text-surface-800">{m.name}</td>
										<td>
											<span class="badge {getProviderBadgeClass(m.provider)}">
												{m.provider}
											</span>
										</td>
										<td class="text-right font-mono text-surface-600">{formatCurrency(m.input)}</td>
										<td class="text-right font-mono text-surface-600">{formatCurrency(m.output)}</td>
										<td class="text-center">
											<div class="flex justify-center gap-2">
												<button
													on:click={() => selectModelForOverride(m)}
													class="text-xs text-primary-600 hover:text-primary-700 font-medium"
												>
													Override
												</button>
												{#if m.provider === 'custom'}
													<button
														on:click={() => deleteOverride(m.name)}
														class="text-xs text-red-500 hover:text-red-600 font-medium"
													>
														Delete
													</button>
												{/if}
											</div>
										</td>
									</tr>
								{/each}
							</tbody>
						</table>
					</div>
				</div>

				<!-- Override Form -->
				<div class="lg:col-span-2">
					<div class="bg-gradient-to-br from-primary-50 to-accent-50 rounded-2xl p-5 border border-primary-100">
						<h3 class="font-semibold text-surface-800 mb-1">Set Price Override</h3>
						<p class="text-xs text-surface-500 mb-5">
							Override pricing for a model or add a custom model.
						</p>
						<div class="space-y-4">
							<label class="block">
								<span class="label">Model Name</span>
								<input
									type="text"
									bind:value={overrideModel}
									placeholder="e.g., gpt-4o or my-custom-model"
									class="input"
								/>
							</label>
							<div class="grid grid-cols-2 gap-3">
								<label class="block">
									<span class="label">Input ($/1M)</span>
									<input
										type="number"
										step="0.01"
										bind:value={overrideInput}
										class="input"
									/>
								</label>
								<label class="block">
									<span class="label">Output ($/1M)</span>
									<input
										type="number"
										step="0.01"
										bind:value={overrideOutput}
										class="input"
									/>
								</label>
							</div>
							<label class="block">
								<span class="label">Description (optional)</span>
								<input
									type="text"
									bind:value={overrideDescription}
									placeholder="e.g., Enterprise discount rate"
									class="input"
								/>
							</label>
							<button
								on:click={saveOverride}
								disabled={overrideLoading}
								class="btn-primary w-full disabled:opacity-50"
							>
								{overrideLoading ? 'Saving...' : 'Save Override'}
							</button>
						</div>
					</div>
				</div>
			</div>
		</div>
	{/if}

	<div class="grid grid-cols-1 lg:grid-cols-2 gap-3">
		<!-- Input Form -->
		<div class="card p-4">
			<h2 class="text-base font-bold text-surface-800 mb-2">Configuration</h2>

			<div class="space-y-2">
				<label class="block">
					<span class="label">Model</span>
					<select bind:value={model} class="select">
						{#each models as m}
							<option value={m.name}>{m.name} ({m.provider})</option>
						{/each}
					</select>
				</label>

				<label class="block">
					<span class="label">Input Tokens per Request</span>
					<input
						type="number"
						bind:value={inputTokens}
						min="1"
						class="input"
					/>
				</label>

				<label class="block">
					<span class="label">Output Tokens per Request</span>
					<input
						type="number"
						bind:value={outputTokens}
						min="1"
						class="input"
					/>
				</label>

				<div class="grid grid-cols-2 gap-4">
					<label class="block">
						<span class="label">Requests per Day</span>
						<input
							type="number"
							bind:value={requestsPerDay}
							min="1"
							class="input"
						/>
					</label>
					<label class="block">
						<span class="label">Days per Month</span>
						<input
							type="number"
							bind:value={daysPerMonth}
							min="1"
							max="31"
							class="input"
						/>
					</label>
				</div>

				<button
					on:click={calculate}
					disabled={loading}
					class="btn-primary w-full text-sm py-2 disabled:opacity-50"
				>
					{loading ? 'Calculating...' : 'Calculate Cost'}
				</button>
			</div>
		</div>

		<!-- Results -->
		<div class="card p-4">
			<h2 class="text-base font-bold text-surface-800 mb-2">Cost Estimate</h2>

			{#if error}
				<div class="bg-red-50 text-red-700 p-2 rounded-lg border border-red-100 text-sm">{error}</div>
			{:else if result}
				<div class="space-y-2 animate-fade-in">
					<!-- Main stat -->
					<div class="bg-gradient-to-br from-primary-500 to-accent-500 rounded-lg p-3 text-center text-white">
						<p class="text-primary-100 text-xs font-medium">Monthly Cost</p>
						<p class="text-2xl font-bold">{formatCurrency(result.monthly_cost)}</p>
					</div>

					<!-- Secondary stats -->
					<div class="grid grid-cols-2 gap-2">
						<div class="bg-surface-50 rounded-lg p-2 border border-surface-100 text-center">
							<p class="text-xs text-surface-500">Daily</p>
							<p class="text-lg font-bold text-primary-600">{formatCurrency(result.daily_cost)}</p>
						</div>
						<div class="bg-surface-50 rounded-lg p-2 border border-surface-100 text-center">
							<p class="text-xs text-surface-500">Yearly</p>
							<p class="text-lg font-bold text-primary-600">{formatCurrency(result.yearly_cost)}</p>
						</div>
					</div>

					<!-- Combined breakdown -->
					<div class="bg-surface-50 rounded-lg p-2 border border-surface-100">
						<div class="grid grid-cols-2 gap-x-4 gap-y-1 text-xs">
							<div class="flex justify-between">
								<span class="text-surface-500">Input/mo</span>
								<span class="font-mono text-surface-700">{formatNumber(result.total_input_tokens)}</span>
							</div>
							<div class="flex justify-between">
								<span class="text-surface-500">Output/mo</span>
								<span class="font-mono text-surface-700">{formatNumber(result.total_output_tokens)}</span>
							</div>
							<div class="flex justify-between">
								<span class="text-surface-500">Input $/day</span>
								<span class="font-mono text-surface-700">{formatCurrency(result.breakdown.input_cost_per_day)}</span>
							</div>
							<div class="flex justify-between">
								<span class="text-surface-500">Output $/day</span>
								<span class="font-mono text-surface-700">{formatCurrency(result.breakdown.output_cost_per_day)}</span>
							</div>
						</div>
					</div>

					<!-- Pricing info -->
					<div class="flex justify-between text-xs bg-surface-50 rounded-lg p-2 border border-surface-100">
						<div>
							<span class="text-surface-400">Input/1M:</span>
							<span class="font-mono font-semibold text-surface-700 ml-1">{formatCurrency(result.breakdown.input_price_per_1m)}</span>
						</div>
						<div>
							<span class="text-surface-400">Output/1M:</span>
							<span class="font-mono font-semibold text-surface-700 ml-1">{formatCurrency(result.breakdown.output_price_per_1m)}</span>
						</div>
					</div>
				</div>
			{:else}
				<div class="text-center py-8">
					<div class="w-12 h-12 rounded-xl bg-surface-100 flex items-center justify-center mx-auto mb-2">
						<svg class="w-6 h-6 text-surface-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
							<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 7h6m0 10v-3m-3 3h.01M9 17h.01M9 14h.01M12 14h.01M15 11h.01M12 11h.01M9 11h.01M7 21h10a2 2 0 002-2V5a2 2 0 00-2-2H7a2 2 0 00-2 2v14a2 2 0 002 2z" />
						</svg>
					</div>
					<p class="text-surface-400 text-sm">Configure and click Calculate</p>
				</div>
			{/if}
		</div>
	</div>
</div>
