<script lang="ts">
	import DashboardSection from '$lib/components/molecules/DashboardSection.svelte';
	import SkeletonList from '$lib/components/atoms/Skeleton/SkeletonList.svelte';
	import { getApiBaseUrl } from '$lib/api/config';
	import { authenticatedFetch, isAuthenticated } from '$lib/auth';
	import { goto } from '$app/navigation';
	import { untrack } from 'svelte';

	let {
		isLoading = false,
		hasRealData = false
	}: {
		isLoading?: boolean;
		hasRealData?: boolean;
	} = $props();

	interface ReplacedClass {
		replacementId: string;
		replacedTeacherId: string;
		classId: string;
		subjectId: string;
		className: string;
		subjectName: string;
		startDate: string;
		endDate: string;
	}

	let replacedClasses = $state<ReplacedClass[]>([]);
	let replacementsLoading = $state(false);

	$effect(() => {
		untrack(() => {
			if (isAuthenticated()) {
				loadReplacedClasses();
			}
		});
	});

	async function loadReplacedClasses() {
		try {
			replacementsLoading = true;
			const apiUrl = getApiBaseUrl();
			const response = await authenticatedFetch(`${apiUrl}/me/replaced-classes`);

			if (!response.ok) return;

			const data = await response.json();
			replacedClasses = Array.isArray(data) ? data : (data['hydra:member'] ?? []);
		} catch {
			// Silently fail - not critical for dashboard display
		} finally {
			replacementsLoading = false;
		}
	}

	function daysRemaining(endDate: string): number {
		const end = new Date(endDate);
		const now = new Date();
		now.setHours(0, 0, 0, 0);
		end.setHours(0, 0, 0, 0);
		return Math.ceil((end.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
	}
</script>

<div class="dashboard-teacher">
	<header class="dashboard-header">
		<h1>Tableau de bord Enseignant</h1>
		<p class="dashboard-subtitle">Bienvenue ! Voici vos outils du jour.</p>
	</header>

	<div class="quick-actions">
		<h2 class="sr-only">Actions rapides</h2>
		<div class="action-cards">
			<button type="button" class="action-card" disabled={!hasRealData}>
				<span class="action-icon">📋</span>
				<span class="action-label">Faire l'appel</span>
			</button>
			<button type="button" class="action-card" disabled={!hasRealData}>
				<span class="action-icon">📝</span>
				<span class="action-label">Saisir des notes</span>
			</button>
			<button type="button" class="action-card" onclick={() => goto('/dashboard/teacher/homework')}>
				<span class="action-icon">📚</span>
				<span class="action-label">Créer un devoir</span>
			</button>
		</div>
	</div>

	{#if replacedClasses.length > 0}
		<DashboardSection
			title="Classes en remplacement"
			subtitle="Vous remplacez actuellement un enseignant"
		>
			<div class="replacement-list">
				{#each replacedClasses as rc}
					{@const days = daysRemaining(rc.endDate)}
					<div class="replacement-card">
						<div class="replacement-badge">Remplacement</div>
						<div class="replacement-info">
							<span class="replacement-class">{rc.className}</span>
							<span class="replacement-subject">{rc.subjectName}</span>
						</div>
						<div class="replacement-dates">
							{new Date(rc.startDate).toLocaleDateString('fr-FR')}
							&rarr;
							{new Date(rc.endDate).toLocaleDateString('fr-FR')}
							<span class="replacement-countdown" class:urgent={days <= 3}>
								{#if days > 1}
									({days} jours restants)
								{:else if days === 1}
									(1 jour restant)
								{:else}
									(Dernier jour)
								{/if}
							</span>
						</div>
					</div>
				{/each}
			</div>
		</DashboardSection>
	{:else if replacementsLoading}
		<DashboardSection title="Classes en remplacement">
			<SkeletonList items={2} message="Chargement des remplacements..." />
		</DashboardSection>
	{/if}

	<div class="dashboard-grid">
		<DashboardSection
			title="Mes classes aujourd'hui"
			isPlaceholder={!hasRealData}
			placeholderMessage="Vos classes apparaîtront ici une fois l'emploi du temps configuré"
		>
			{#if hasRealData && isLoading}
				<SkeletonList items={4} message="Chargement des classes..." />
			{/if}
		</DashboardSection>

		<DashboardSection
			title="Notes à saisir"
			subtitle="Évaluations en attente"
			isPlaceholder={!hasRealData}
			placeholderMessage="Les évaluations en attente de notation seront listées ici"
		>
			{#if hasRealData && isLoading}
				<SkeletonList items={3} message="Chargement des évaluations..." />
			{/if}
		</DashboardSection>

		<DashboardSection
			title="Appels du jour"
			isPlaceholder={!hasRealData}
			placeholderMessage="Les appels à effectuer s'afficheront ici"
		>
			{#if hasRealData && isLoading}
				<SkeletonList items={3} message="Chargement des appels..." />
			{/if}
		</DashboardSection>

		<DashboardSection
			title="Statistiques rapides"
			isPlaceholder={!hasRealData}
			placeholderMessage="Les statistiques de vos classes seront disponibles prochainement"
		>
			{#if hasRealData && isLoading}
				<SkeletonList items={2} message="Chargement des statistiques..." />
			{/if}
		</DashboardSection>
	</div>
</div>

<style>
	.dashboard-teacher {
		display: flex;
		flex-direction: column;
		gap: 1.5rem;
	}

	.dashboard-header {
		margin-bottom: 0.5rem;
	}

	.dashboard-header h1 {
		margin: 0;
		font-size: 1.5rem;
		font-weight: 700;
		color: #1f2937;
	}

	.dashboard-subtitle {
		margin: 0.25rem 0 0;
		color: #6b7280;
	}

	.sr-only {
		position: absolute;
		width: 1px;
		height: 1px;
		padding: 0;
		margin: -1px;
		overflow: hidden;
		clip: rect(0, 0, 0, 0);
		white-space: nowrap;
		border: 0;
	}

	.quick-actions {
		margin-bottom: 0.5rem;
	}

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

	.action-card {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 0.5rem;
		padding: 1.25rem 1rem;
		background: white;
		border: 2px solid #e5e7eb;
		border-radius: 0.75rem;
		cursor: pointer;
		transition: all 0.2s;
	}

	.action-card:hover:not(:disabled) {
		border-color: #3b82f6;
		background: #eff6ff;
	}

	.action-card:disabled {
		opacity: 0.6;
		cursor: not-allowed;
	}

	.action-icon {
		font-size: 1.75rem;
	}

	.action-label {
		font-weight: 500;
		color: #374151;
		text-align: center;
		font-size: 0.875rem;
	}

	.dashboard-grid {
		display: grid;
		gap: 1.5rem;
		grid-template-columns: 1fr;
	}

	/* Replacement section */
	.replacement-list {
		display: flex;
		flex-direction: column;
		gap: 0.75rem;
	}

	.replacement-card {
		padding: 0.75rem 1rem;
		background: #eff6ff;
		border: 1px solid #bfdbfe;
		border-radius: 0.5rem;
	}

	.replacement-badge {
		display: inline-block;
		padding: 0.125rem 0.5rem;
		background: var(--btn-primary-bg, #3b82f6);
		color: white;
		border-radius: 9999px;
		font-size: 0.6875rem;
		font-weight: 600;
		margin-bottom: 0.5rem;
	}

	.replacement-info {
		display: flex;
		gap: 0.5rem;
		align-items: center;
		margin-bottom: 0.25rem;
	}

	.replacement-class {
		font-weight: 600;
		color: #1f2937;
	}

	.replacement-subject {
		color: #4b5563;
		font-size: 0.875rem;
	}

	.replacement-dates {
		font-size: 0.8125rem;
		color: #6b7280;
	}

	.replacement-countdown {
		font-weight: 500;
		color: #16a34a;
	}

	.replacement-countdown.urgent {
		color: #dc2626;
	}

	@media (min-width: 768px) {
		.dashboard-grid {
			grid-template-columns: repeat(2, 1fr);
		}
	}
</style>
