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

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

	let file: File | null = null;
	let fileName = '';
	let loading = false;
	let error = '';
	let result: any = null;
	let activeTab: 'overview' | 'columns' | 'issues' = 'overview';

	function handleFileSelect(event: Event) {
		const input = event.target as HTMLInputElement;
		if (input.files && input.files[0]) {
			file = input.files[0];
			fileName = file.name;
			result = null;
			error = '';
		}
	}

	function handleDrop(event: DragEvent) {
		event.preventDefault();
		if (event.dataTransfer?.files && event.dataTransfer.files[0]) {
			file = event.dataTransfer.files[0];
			fileName = file.name;
			result = null;
			error = '';
		}
	}

	function handleDragOver(event: DragEvent) {
		event.preventDefault();
	}

	async function analyzeData() {
		if (!file) {
			error = 'Please select a file first';
			return;
		}

		loading = true;
		error = '';
		result = null;

		try {
			const formData = new FormData();
			formData.append('file', file);

			const response = await fetch(`${API_BASE}/audit/analyze`, {
				method: 'POST',
				body: formData
			});

			if (!response.ok) {
				const errData = await response.json();
				throw new Error(errData.detail || 'Analysis failed');
			}

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

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

	function getIssueIcon(issue: string): string {
		if (issue.includes('missing')) return '!';
		if (issue.includes('duplicate')) return '2x';
		if (issue.includes('outlier')) return '~';
		if (issue.includes('cardinality')) return '#';
		if (issue.includes('constant')) return '=';
		if (issue.includes('No major')) return 'OK';
		return '!';
	}

	function getIssueColor(issue: string): string {
		if (issue.includes('No major')) return 'text-green-600 bg-green-50 border-green-200';
		if (issue.includes('outlier')) return 'text-yellow-600 bg-yellow-50 border-yellow-200';
		return 'text-red-600 bg-red-50 border-red-200';
	}
</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">Data Integrity Audit</h1>
		<p class="text-surface-600 mt-1">Upload a dataset to analyze for quality issues, missing values, and outliers</p>
	</div>

	<div class="grid grid-cols-1 lg:grid-cols-3 gap-4">
		<!-- Upload Section -->
		<div class="card p-4">
			<h2 class="text-base font-bold text-surface-800 mb-3">Upload Dataset</h2>

			<!-- Drop Zone -->
			<div
				class="border-2 border-dashed border-surface-300 rounded-xl p-6 text-center hover:border-primary-400 transition-colors cursor-pointer"
				on:drop={handleDrop}
				on:dragover={handleDragOver}
				role="button"
				tabindex="0"
			>
				<input
					type="file"
					accept=".csv,.xlsx,.xls,.json"
					on:change={handleFileSelect}
					class="hidden"
					id="file-input"
				/>
				<label for="file-input" class="cursor-pointer">
					<div class="w-12 h-12 rounded-xl bg-primary-100 flex items-center justify-center mx-auto mb-3">
						<svg class="w-6 h-6 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
							<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
						</svg>
					</div>
					<p class="text-sm text-surface-600">
						<span class="text-primary-600 font-medium">Click to upload</span> or drag and drop
					</p>
					<p class="text-xs text-surface-400 mt-1">CSV, Excel, or JSON files</p>
				</label>
			</div>

			{#if fileName}
				<div class="mt-3 flex items-center gap-2 p-2 bg-surface-50 rounded-lg">
					<svg class="w-4 h-4 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
						<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
					</svg>
					<span class="text-sm text-surface-700 truncate flex-1">{fileName}</span>
				</div>
			{/if}

			<button
				on:click={analyzeData}
				disabled={loading || !file}
				class="btn-primary w-full mt-4 disabled:opacity-50"
			>
				{loading ? 'Analyzing...' : 'Analyze Data'}
			</button>

			{#if error}
				<div class="mt-3 p-2 bg-red-50 text-red-700 text-sm rounded-lg border border-red-100">
					{error}
				</div>
			{/if}
		</div>

		<!-- Results Section -->
		<div class="lg:col-span-2 card p-4">
			<h2 class="text-base font-bold text-surface-800 mb-3">Analysis Results</h2>

			{#if result}
				<!-- Quick Stats -->
				<div class="grid grid-cols-4 gap-2 mb-4">
					<div class="bg-surface-50 rounded-lg p-3 text-center border border-surface-100">
						<p class="text-xs text-surface-600">Rows</p>
						<p class="text-lg font-bold text-surface-800">{formatNumber(result.total_rows)}</p>
					</div>
					<div class="bg-surface-50 rounded-lg p-3 text-center border border-surface-100">
						<p class="text-xs text-surface-600">Columns</p>
						<p class="text-lg font-bold text-surface-800">{result.total_columns}</p>
					</div>
					<div class="bg-surface-50 rounded-lg p-3 text-center border border-surface-100">
						<p class="text-xs text-surface-600">Duplicates</p>
						<p class="text-lg font-bold {result.duplicate_rows > 0 ? 'text-yellow-600' : 'text-green-600'}">
							{formatNumber(result.duplicate_rows)}
						</p>
					</div>
					<div class="bg-surface-50 rounded-lg p-3 text-center border border-surface-100">
						<p class="text-xs text-surface-600">Issues</p>
						<p class="text-lg font-bold {result.issues.length > 1 || !result.issues[0]?.includes('No major') ? 'text-red-600' : 'text-green-600'}">
							{result.issues[0]?.includes('No major') ? 0 : result.issues.length}
						</p>
					</div>
				</div>

				<!-- Tabs -->
				<div class="flex gap-1 mb-4 border-b border-surface-200">
					<button
						class="px-4 py-2 text-sm font-medium transition-colors {activeTab === 'overview' ? 'text-primary-600 border-b-2 border-primary-600' : 'text-surface-500 hover:text-surface-700'}"
						on:click={() => activeTab = 'overview'}
					>
						Overview
					</button>
					<button
						class="px-4 py-2 text-sm font-medium transition-colors {activeTab === 'columns' ? 'text-primary-600 border-b-2 border-primary-600' : 'text-surface-500 hover:text-surface-700'}"
						on:click={() => activeTab = 'columns'}
					>
						Columns ({result.column_stats.length})
					</button>
					<button
						class="px-4 py-2 text-sm font-medium transition-colors {activeTab === 'issues' ? 'text-primary-600 border-b-2 border-primary-600' : 'text-surface-500 hover:text-surface-700'}"
						on:click={() => activeTab = 'issues'}
					>
						Issues & Recommendations
					</button>
				</div>

				<!-- Tab Content -->
				{#if activeTab === 'overview'}
					<div class="space-y-3">
						<!-- Missing Values Summary -->
						{#if Object.keys(result.missing_values).length > 0}
							<div class="bg-yellow-50 rounded-lg p-3 border border-yellow-200">
								<h3 class="text-sm font-semibold text-yellow-800 mb-2">Missing Values</h3>
								<div class="grid grid-cols-2 gap-2 text-xs">
									{#each Object.entries(result.missing_values) as [col, info]}
										<div class="flex justify-between">
											<span class="text-yellow-700">{col}</span>
											<span class="font-mono text-yellow-800">{info.count} ({info.percent}%)</span>
										</div>
									{/each}
								</div>
							</div>
						{:else}
							<div class="bg-green-50 rounded-lg p-3 border border-green-200">
								<p class="text-sm text-green-700">No missing values detected</p>
							</div>
						{/if}

						<!-- Duplicates -->
						<div class="{result.duplicate_rows > 0 ? 'bg-yellow-50 border-yellow-200' : 'bg-green-50 border-green-200'} rounded-lg p-3 border">
							<p class="text-sm {result.duplicate_rows > 0 ? 'text-yellow-700' : 'text-green-700'}">
								{#if result.duplicate_rows > 0}
									{formatNumber(result.duplicate_rows)} duplicate rows found ({result.duplicate_percent}%)
								{:else}
									No duplicate rows detected
								{/if}
							</p>
						</div>
					</div>
				{:else if activeTab === 'columns'}
					<div class="overflow-x-auto">
						<table class="table-modern">
							<thead>
								<tr>
									<th>Column</th>
									<th>Type</th>
									<th class="text-right">Missing</th>
									<th class="text-right">Unique</th>
									<th>Sample</th>
								</tr>
							</thead>
							<tbody>
								{#each result.column_stats as col}
									<tr>
										<td class="font-medium text-surface-800">{col.name}</td>
										<td>
											<span class="text-xs px-2 py-0.5 rounded bg-surface-100 text-surface-600 font-mono">
												{col.dtype}
											</span>
										</td>
										<td class="text-right">
											<span class="{col.missing_count > 0 ? 'text-yellow-600' : 'text-surface-500'}">
												{col.missing_count} ({col.missing_percent}%)
											</span>
										</td>
										<td class="text-right text-surface-600">{formatNumber(col.unique_count)}</td>
										<td class="text-xs text-surface-500 max-w-[150px] truncate">
											{col.sample_values.slice(0, 3).join(', ')}
										</td>
									</tr>
								{/each}
							</tbody>
						</table>
					</div>
				{:else if activeTab === 'issues'}
					<div class="space-y-4">
						<!-- Issues -->
						<div>
							<h3 class="text-sm font-semibold text-surface-700 mb-2">Issues Found</h3>
							<div class="space-y-2">
								{#each result.issues as issue}
									<div class="flex items-start gap-2 p-2 rounded-lg border {getIssueColor(issue)}">
										<span class="text-xs font-bold w-6 h-6 rounded flex items-center justify-center bg-white/50">
											{getIssueIcon(issue)}
										</span>
										<span class="text-sm">{issue}</span>
									</div>
								{/each}
							</div>
						</div>

						<!-- Recommendations -->
						<div>
							<h3 class="text-sm font-semibold text-surface-700 mb-2">Recommendations</h3>
							<div class="space-y-2">
								{#each result.recommendations as rec}
									<div class="flex items-start gap-2 p-2 rounded-lg bg-primary-50 border border-primary-100">
										<svg class="w-4 h-4 text-primary-600 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
											<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
										</svg>
										<span class="text-sm text-primary-700">{rec}</span>
									</div>
								{/each}
							</div>
						</div>
					</div>
				{/if}
			{:else}
				<div class="text-center py-12">
					<div class="w-16 h-16 rounded-2xl bg-surface-100 flex items-center justify-center mx-auto mb-4">
						<svg class="w-8 h-8 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 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
						</svg>
					</div>
					<p class="text-surface-500">Upload a dataset to see analysis results</p>
				</div>
			{/if}
		</div>
	</div>
</div>
