<script lang="ts">
	import { getApiBaseUrl } from '$lib/api';
	import { authenticatedFetch, getAuthenticatedUserId } from '$lib/auth';
	import CompetencyProgressBar from '$lib/components/organisms/CompetencyProgress/CompetencyProgressBar.svelte';

	interface CompetencyLevel {
		code: string;
		name: string;
		color: string | null;
		sortOrder: number;
	}

	interface CompetencyProgress {
		competencyId: string;
		competencyCode: string;
		competencyName: string;
		currentLevelCode: string | null;
		currentLevelName: string | null;
		history: Array<{ date: string; levelCode: string; evaluationTitle: string }>;
	}

	let levels: CompetencyLevel[] = $state([]);
	let progress: CompetencyProgress[] = $state([]);
	let isLoading = $state(true);
	let error: string | null = $state(null);
	let selectedCompetencyId: string | null = $state(null);

	let selectedHistory = $derived.by(() => {
		if (!selectedCompetencyId) return null;
		return progress.find((p) => p.competencyId === selectedCompetencyId) ?? null;
	});

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

	async function loadAll() {
		try {
			isLoading = true;
			error = null;
			const apiUrl = getApiBaseUrl();
			const userId = await getAuthenticatedUserId();
			if (!userId) throw new Error('Non authentifié');

			const [levelsRes, progressRes] = await Promise.all([
				authenticatedFetch(`${apiUrl}/competency-levels`),
				authenticatedFetch(`${apiUrl}/students/${userId}/competency-progress`),
			]);

			if (!levelsRes.ok) throw new Error('Erreur lors du chargement des niveaux');
			if (!progressRes.ok) throw new Error('Erreur lors du chargement de la progression');

			const levelsData = await levelsRes.json();
			levels = (levelsData['hydra:member'] ?? levelsData['member'] ?? (Array.isArray(levelsData) ? levelsData : [])) as CompetencyLevel[];

			const progressData = await progressRes.json();
			progress = (progressData['hydra:member'] ?? progressData['member'] ?? (Array.isArray(progressData) ? progressData : [])) as CompetencyProgress[];
		} catch (e) {
			error = e instanceof Error ? e.message : 'Erreur inconnue';
		} finally {
			isLoading = false;
		}
	}

	function getLevelColor(levelCode: string): string {
		const level = levels.find((l) => l.code === levelCode);
		return level?.color ?? '#94a3b8';
	}

	function getLevelName(levelCode: string): string {
		const level = levels.find((l) => l.code === levelCode);
		return level?.name ?? levelCode;
	}

	function formatDate(dateStr: string | null): string {
		if (!dateStr) return '-';
		try {
			return new Intl.DateTimeFormat('fr-FR', {
				day: 'numeric',
				month: 'long',
				year: 'numeric',
			}).format(new Date(dateStr));
		} catch {
			return dateStr;
		}
	}
</script>

<svelte:head>
	<title>Mes compétences - Classeo</title>
</svelte:head>

<div class="competencies-page">
	<h1>Mes compétences</h1>

	{#if error}
		<div class="error-banner" role="alert">
			<p>{error}</p>
			<button onclick={() => (error = null)}>Fermer</button>
		</div>
	{/if}

	{#if isLoading}
		<div class="loading-state" aria-live="polite" role="status">
			<div class="spinner"></div>
			<p>Chargement de vos compétences...</p>
		</div>
	{:else if progress.length === 0}
		<div class="empty-state">
			<h2>Aucune compétence évaluée</h2>
			<p>Vos résultats de compétences apparaîtront ici dès qu'une évaluation par compétences sera complétée.</p>
		</div>
	{:else}
		<section class="synthesis-section">
			<h2>Synthèse</h2>
			<CompetencyProgressBar {progress} {levels} />
		</section>

		<section class="detail-section">
			<h2>Détail par compétence</h2>
			<p class="detail-hint">Cliquez sur une compétence pour voir l'historique de progression.</p>

			<div class="competency-cards">
				{#each progress as item (item.competencyId)}
					<button
						class="competency-card"
						class:selected={selectedCompetencyId === item.competencyId}
						onclick={() => {
							selectedCompetencyId = selectedCompetencyId === item.competencyId ? null : item.competencyId;
						}}
					>
						<div class="card-header">
							<span class="card-code">{item.competencyCode}</span>
							{#if item.currentLevelCode}
								<span
									class="card-badge"
									style="background-color: {getLevelColor(item.currentLevelCode)}"
								>
									{item.currentLevelName}
								</span>
							{:else}
								<span class="card-badge card-badge-empty">Non évalué</span>
							{/if}
						</div>
						<div class="card-name">{item.competencyName}</div>
						{#if item.history.length > 1}
							<div class="card-evals">{item.history.length} évaluations</div>
						{/if}
					</button>
				{/each}
			</div>

			{#if selectedHistory}
				<div class="history-panel">
					<h3>Historique : {selectedHistory.competencyCode} - {selectedHistory.competencyName}</h3>
					<div class="history-timeline">
						{#each selectedHistory.history as entry, i (i)}
							<div class="timeline-entry">
								<div
									class="timeline-dot"
									style="background-color: {getLevelColor(entry.levelCode)}"
								></div>
								<div class="timeline-content">
									<span class="timeline-level" style="color: {getLevelColor(entry.levelCode)}">
										{getLevelName(entry.levelCode)}
									</span>
									<span class="timeline-eval">{entry.evaluationTitle}</span>
									<span class="timeline-date">{formatDate(entry.date)}</span>
								</div>
							</div>
						{/each}
					</div>
				</div>
			{/if}
		</section>
	{/if}
</div>

<style>
	.competencies-page {
		padding: 1.5rem;
		max-width: 900px;
		margin: 0 auto;
	}

	h1 {
		font-size: 1.5rem;
		font-weight: 600;
		margin-bottom: 1.5rem;
	}

	h2 {
		font-size: 1.125rem;
		font-weight: 600;
		margin-bottom: 1rem;
	}

	.error-banner {
		background: var(--color-error-bg, #fee2e2);
		color: var(--color-error, #dc2626);
		padding: 0.75rem 1rem;
		border-radius: 0.5rem;
		margin-bottom: 1rem;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.error-banner p { margin: 0; }
	.error-banner button {
		background: none;
		border: none;
		color: var(--color-error, #dc2626);
		cursor: pointer;
		font-weight: 600;
	}

	.loading-state, .empty-state {
		text-align: center;
		padding: 3rem;
		color: var(--color-text-secondary, #64748b);
	}

	.spinner {
		width: 2rem;
		height: 2rem;
		border: 3px solid var(--color-border, #e2e8f0);
		border-top-color: var(--color-primary, #3b82f6);
		border-radius: 50%;
		animation: spin 0.8s linear infinite;
		margin: 0 auto 1rem;
	}

	@keyframes spin { to { transform: rotate(360deg); } }

	.synthesis-section {
		margin-bottom: 2rem;
		padding: 1.25rem;
		background: var(--color-surface, #fff);
		border-radius: 0.75rem;
		border: 1px solid var(--color-border, #e2e8f0);
	}

	.detail-section {
		margin-bottom: 2rem;
	}

	.detail-hint {
		font-size: 0.875rem;
		color: var(--color-text-secondary, #64748b);
		margin-bottom: 1rem;
	}

	.competency-cards {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
		gap: 0.75rem;
		margin-bottom: 1.5rem;
	}

	.competency-card {
		background: var(--color-surface, #fff);
		border: 1px solid var(--color-border, #e2e8f0);
		border-radius: 0.5rem;
		padding: 0.75rem 1rem;
		text-align: left;
		cursor: pointer;
		transition: all 0.15s ease;
		width: 100%;
		font-family: inherit;
		font-size: inherit;
	}

	.competency-card:hover {
		border-color: var(--color-primary, #3b82f6);
	}

	.competency-card.selected {
		border-color: var(--color-primary, #3b82f6);
		box-shadow: 0 0 0 1px var(--color-primary, #3b82f6);
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 0.375rem;
	}

	.card-code {
		font-weight: 700;
		font-size: 0.875rem;
	}

	.card-badge {
		padding: 0.125rem 0.5rem;
		border-radius: 1rem;
		font-size: 0.7rem;
		font-weight: 600;
		color: #fff;
	}

	.card-badge-empty {
		background: var(--color-text-secondary, #94a3b8);
	}

	.card-name {
		font-size: 0.8rem;
		color: var(--color-text-secondary, #64748b);
	}

	.card-evals {
		font-size: 0.7rem;
		color: var(--color-text-tertiary, #a1a1aa);
		margin-top: 0.375rem;
	}

	.history-panel {
		background: var(--color-surface, #fff);
		border: 1px solid var(--color-border, #e2e8f0);
		border-radius: 0.75rem;
		padding: 1.25rem;
	}

	.history-panel h3 {
		font-size: 1rem;
		font-weight: 600;
		margin-bottom: 1rem;
	}

	.history-timeline {
		display: flex;
		flex-direction: column;
		gap: 0.75rem;
		padding-left: 1rem;
		border-left: 2px solid var(--color-border, #e2e8f0);
	}

	.timeline-entry {
		display: flex;
		align-items: flex-start;
		gap: 0.75rem;
		position: relative;
	}

	.timeline-dot {
		width: 0.75rem;
		height: 0.75rem;
		border-radius: 50%;
		flex-shrink: 0;
		margin-top: 0.25rem;
		margin-left: -1.375rem;
	}

	.timeline-content {
		display: flex;
		flex-direction: column;
		gap: 0.125rem;
	}

	.timeline-level {
		font-weight: 600;
		font-size: 0.875rem;
	}

	.timeline-eval {
		font-size: 0.8rem;
		color: var(--color-text, #1e293b);
	}

	.timeline-date {
		font-size: 0.75rem;
		color: var(--color-text-secondary, #64748b);
	}
</style>
