<script lang="ts">
	import { onMount } from 'svelte';
	import {
		getEstablishments,
		getMetrics,
		switchTenant,
		type EstablishmentData,
		type EstablishmentMetrics
	} from '$lib/features/super-admin/api/super-admin';

	let establishments = $state<EstablishmentData[]>([]);
	let metrics = $state<EstablishmentMetrics[]>([]);
	let isLoading = $state(true);
	let error = $state<string | null>(null);

	let totalUsers = $derived(metrics.reduce((sum, m) => sum + m.userCount, 0));
	let totalStudents = $derived(metrics.reduce((sum, m) => sum + m.studentCount, 0));
	let totalTeachers = $derived(metrics.reduce((sum, m) => sum + m.teacherCount, 0));
	let activeCount = $derived(establishments.filter((e) => e.status === 'active').length);

	onMount(async () => {
		try {
			const [estData, metricsData] = await Promise.all([getEstablishments(), getMetrics()]);
			establishments = estData;
			metrics = metricsData;
		} catch (e) {
			error = e instanceof Error ? e.message : 'Erreur inconnue';
		} finally {
			isLoading = false;
		}
	});

	async function handleSwitch(tenantId: string) {
		try {
			await switchTenant(tenantId);
			window.location.href = '/dashboard';
		} catch (e) {
			error = e instanceof Error ? e.message : 'Erreur lors du basculement';
		}
	}
</script>

<div class="sa-dashboard">
	<h2>Dashboard</h2>

	{#if error}
		<div class="error-banner">{error}</div>
	{/if}

	{#if isLoading}
		<div class="loading">Chargement...</div>
	{:else}
		<div class="stats-grid">
			<div class="stat-card">
				<span class="stat-value">{establishments.length}</span>
				<span class="stat-label">Établissements</span>
			</div>
			<div class="stat-card">
				<span class="stat-value">{activeCount}</span>
				<span class="stat-label">Actifs</span>
			</div>
			<div class="stat-card">
				<span class="stat-value">{totalUsers}</span>
				<span class="stat-label">Utilisateurs</span>
			</div>
			<div class="stat-card">
				<span class="stat-value">{totalStudents}</span>
				<span class="stat-label">Élèves</span>
			</div>
			<div class="stat-card">
				<span class="stat-value">{totalTeachers}</span>
				<span class="stat-label">Enseignants</span>
			</div>
		</div>

		<h3>Établissements</h3>
		{#if establishments.length === 0}
			<p class="empty">Aucun établissement. <a href="/super-admin/establishments/new">Créer le premier</a></p>
		{:else}
			<div class="establishments-grid">
				{#each establishments as establishment}
					{@const metricsData = metrics.find((m) => m.establishmentId === establishment.id)}
					<div class="establishment-card">
						<div class="est-header">
							<h4>{establishment.name}</h4>
							<span class="badge" class:active={establishment.status === 'active'}>
								{establishment.status === 'active' ? 'Actif' : 'Inactif'}
							</span>
						</div>
						<p class="est-subdomain">{establishment.subdomain}</p>
						{#if metricsData}
							<div class="est-metrics">
								<span>{metricsData.userCount} utilisateurs</span>
								<span>{metricsData.studentCount} élèves</span>
								<span>{metricsData.teacherCount} enseignants</span>
							</div>
						{/if}
						<div class="est-actions">
							<button
								class="btn-switch"
								onclick={() => handleSwitch(establishment.tenantId)}
							>
								Accéder
							</button>
							<a
								href="/super-admin/establishments/{establishment.id}"
								class="btn-detail"
							>
								Détail
							</a>
						</div>
					</div>
				{/each}
			</div>
		{/if}
	{/if}
</div>

<style>
	.sa-dashboard h2 {
		margin: 0 0 1.5rem;
		font-size: 1.5rem;
		color: #1a1a2e;
	}

	.sa-dashboard h3 {
		margin: 2rem 0 1rem;
		font-size: 1.125rem;
		color: #333;
	}

	.error-banner {
		background: #fee2e2;
		color: #dc2626;
		padding: 0.75rem 1rem;
		border-radius: 8px;
		margin-bottom: 1rem;
	}

	.loading {
		text-align: center;
		color: #666;
		padding: 3rem;
	}

	.stats-grid {
		display: grid;
		grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
		gap: 1rem;
	}

	.stat-card {
		background: white;
		border-radius: 12px;
		padding: 1.25rem;
		text-align: center;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
	}

	.stat-value {
		display: block;
		font-size: 2rem;
		font-weight: 700;
		color: #1a1a2e;
	}

	.stat-label {
		display: block;
		font-size: 0.8125rem;
		color: #666;
		margin-top: 0.25rem;
	}

	.establishments-grid {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
		gap: 1rem;
	}

	.establishment-card {
		background: white;
		border-radius: 12px;
		padding: 1.25rem;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
	}

	.est-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.est-header h4 {
		margin: 0;
		font-size: 1rem;
	}

	.badge {
		font-size: 0.75rem;
		padding: 0.125rem 0.5rem;
		border-radius: 12px;
		background: #fee2e2;
		color: #dc2626;
	}

	.badge.active {
		background: #dcfce7;
		color: #16a34a;
	}

	.est-subdomain {
		font-size: 0.8125rem;
		color: #666;
		margin: 0.5rem 0;
	}

	.est-metrics {
		display: flex;
		gap: 1rem;
		font-size: 0.75rem;
		color: #888;
		margin-bottom: 1rem;
	}

	.est-actions {
		display: flex;
		gap: 0.5rem;
	}

	.btn-switch {
		flex: 1;
		padding: 0.5rem;
		background: #1a1a2e;
		color: white;
		border: none;
		border-radius: 6px;
		cursor: pointer;
		font-size: 0.8125rem;
	}

	.btn-switch:hover {
		background: #16213e;
	}

	.btn-detail {
		padding: 0.5rem 1rem;
		border: 1px solid #ddd;
		border-radius: 6px;
		text-decoration: none;
		color: #333;
		font-size: 0.8125rem;
	}

	.btn-detail:hover {
		background: #f5f5f5;
	}

	.empty {
		color: #666;
		text-align: center;
		padding: 2rem;
	}

	.empty a {
		color: #1a1a2e;
		font-weight: 600;
	}
</style>
