<script lang="ts">
	import { goto } from '$app/navigation';
	import { getApiBaseUrl } from '$lib/api/config';
	import { authenticatedFetch } from '$lib/auth';
	import { SCHOOL_LEVEL_OPTIONS } from '$lib/constants/schoolLevels';

	// Types
	interface SchoolClass {
		id: string;
		name: string;
		level: string | null;
		capacity: number | null;
		status: string;
		createdAt: string;
		updatedAt: string;
	}

	// State
	let classes = $state<SchoolClass[]>([]);
	let isLoading = $state(true);
	let error = $state<string | null>(null);
	let showCreateModal = $state(false);
	let showDeleteModal = $state(false);
	let classToDelete = $state<SchoolClass | null>(null);

	// Form state
	let newClassName = $state('');
	let newClassLevel = $state<string | null>(null);
	let newClassCapacity = $state<number | null>(null);
	let isSubmitting = $state(false);
	let isDeleting = $state(false);

	// Load classes on mount
	$effect(() => {
		loadClasses();
	});

	async function loadClasses() {
		try {
			isLoading = true;
			error = null;
			const apiUrl = getApiBaseUrl();
			const response = await authenticatedFetch(`${apiUrl}/classes`);

			if (!response.ok) {
				throw new Error('Erreur lors du chargement des classes');
			}

			const data = await response.json();
			// API Platform peut retourner hydra:member, member, ou un tableau direct
			classes = data['hydra:member'] ?? data['member'] ?? (Array.isArray(data) ? data : []);
		} catch (e) {
			error = e instanceof Error ? e.message : 'Erreur inconnue';
			// Use demo data for now
			classes = [];
		} finally {
			isLoading = false;
		}
	}

	async function handleCreateClass() {
		if (!newClassName.trim()) return;

		try {
			isSubmitting = true;
			const apiUrl = getApiBaseUrl();
			const response = await authenticatedFetch(`${apiUrl}/classes`, {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify({
					name: newClassName.trim(),
					level: newClassLevel,
					capacity: newClassCapacity
				})
			});

			if (!response.ok) {
				const errorData = await response.json();
				throw new Error(errorData.message || 'Erreur lors de la création');
			}

			// Reload classes and close modal
			await loadClasses();
			closeModal();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Erreur lors de la création';
		} finally {
			isSubmitting = false;
		}
	}

	function openDeleteModal(schoolClass: SchoolClass) {
		classToDelete = schoolClass;
		showDeleteModal = true;
	}

	function closeDeleteModal() {
		showDeleteModal = false;
		classToDelete = null;
	}

	async function handleConfirmDelete() {
		if (!classToDelete) return;

		try {
			isDeleting = true;
			const apiUrl = getApiBaseUrl();
			const response = await authenticatedFetch(`${apiUrl}/classes/${classToDelete.id}`, {
				method: 'DELETE'
			});

			if (!response.ok) {
				const errorData = await response.json();
				throw new Error(errorData.message || 'Erreur lors de la suppression');
			}

			closeDeleteModal();
			await loadClasses();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Erreur lors de la suppression';
		} finally {
			isDeleting = false;
		}
	}

	function openCreateModal() {
		showCreateModal = true;
		newClassName = '';
		newClassLevel = null;
		newClassCapacity = null;
	}

	function closeModal() {
		showCreateModal = false;
	}

	function navigateToEdit(classId: string) {
		goto(`/admin/classes/${classId}`);
	}
</script>

<svelte:head>
	<title>Gestion des classes - Classeo</title>
</svelte:head>

<div class="classes-page">
	<header class="page-header">
		<div class="header-content">
			<h1>Gestion des classes</h1>
			<p class="subtitle">Créez et gérez les classes de votre établissement</p>
		</div>
		<button class="btn-primary" onclick={openCreateModal}>
			<span class="btn-icon">+</span>
			Nouvelle classe
		</button>
	</header>

	{#if error}
		<div class="alert alert-error">
			<span class="alert-icon">⚠️</span>
			{error}
			<button class="alert-close" onclick={() => (error = null)}>×</button>
		</div>
	{/if}

	{#if isLoading}
		<div class="loading-state">
			<div class="spinner"></div>
			<p>Chargement des classes...</p>
		</div>
	{:else if classes.length === 0}
		<div class="empty-state">
			<span class="empty-icon">🏫</span>
			<h2>Aucune classe</h2>
			<p>Commencez par créer votre première classe</p>
			<button class="btn-primary" onclick={openCreateModal}>Créer une classe</button>
		</div>
	{:else}
		<div class="classes-grid">
			{#each classes as schoolClass (schoolClass.id)}
				<div class="class-card">
					<div class="class-info">
						<h3 class="class-name">{schoolClass.name}</h3>
						{#if schoolClass.level}
							<span class="class-level">{schoolClass.level}</span>
						{/if}
					</div>
					<div class="class-meta">
						{#if schoolClass.capacity}
							<span class="meta-item">
								<span class="meta-icon">👥</span>
								{schoolClass.capacity} places
							</span>
						{/if}
						<span class="meta-item status-{schoolClass.status}">
							{schoolClass.status === 'active' ? 'Active' : 'Archivée'}
						</span>
					</div>
					<div class="class-actions">
						<button class="btn-secondary btn-sm" onclick={() => navigateToEdit(schoolClass.id)}>
							Modifier
						</button>
						<button
							class="btn-danger btn-sm"
							onclick={() => openDeleteModal(schoolClass)}
						>
							Supprimer
						</button>
					</div>
				</div>
			{/each}
		</div>
	{/if}
</div>

<!-- Create Modal -->
{#if showCreateModal}
	<!-- svelte-ignore a11y_no_static_element_interactions -->
	<div class="modal-overlay" onclick={closeModal} role="presentation">
		<div
			class="modal"
			role="dialog"
			aria-modal="true"
			aria-labelledby="modal-title"
			tabindex="-1"
			onclick={(e) => e.stopPropagation()}
			onkeydown={(e) => { if (e.key === 'Escape') closeModal(); }}
		>
			<header class="modal-header">
				<h2 id="modal-title">Nouvelle classe</h2>
				<button class="modal-close" onclick={closeModal} aria-label="Fermer">×</button>
			</header>

			<form class="modal-body" onsubmit={(e) => { e.preventDefault(); handleCreateClass(); }}>
				<div class="form-group">
					<label for="class-name">Nom de la classe *</label>
					<input
						type="text"
						id="class-name"
						bind:value={newClassName}
						placeholder="ex: 6ème A"
						required
						minlength="2"
						maxlength="50"
					/>
				</div>

				<div class="form-group">
					<label for="class-level">Niveau scolaire</label>
					<select id="class-level" bind:value={newClassLevel}>
						<option value={null}>-- Sélectionner --</option>
						{#each SCHOOL_LEVEL_OPTIONS as level}
							<option value={level.value}>{level.label}</option>
						{/each}
					</select>
				</div>

				<div class="form-group">
					<label for="class-capacity">Capacité maximale</label>
					<input
						type="number"
						id="class-capacity"
						bind:value={newClassCapacity}
						placeholder="ex: 30"
						min="1"
						max="100"
					/>
				</div>

				<div class="modal-actions">
					<button type="button" class="btn-secondary" onclick={closeModal} disabled={isSubmitting}>
						Annuler
					</button>
					<button type="submit" class="btn-primary" disabled={isSubmitting || !newClassName.trim()}>
						{#if isSubmitting}
							Création...
						{:else}
							Créer la classe
						{/if}
					</button>
				</div>
			</form>
		</div>
	</div>
{/if}

<!-- Delete Confirmation Modal -->
{#if showDeleteModal && classToDelete}
	<!-- svelte-ignore a11y_no_static_element_interactions -->
	<div class="modal-overlay" onclick={closeDeleteModal} role="presentation">
		<div
			class="modal modal-confirm"
			role="alertdialog"
			aria-modal="true"
			aria-labelledby="delete-modal-title"
			aria-describedby="delete-modal-description"
			tabindex="-1"
			onclick={(e) => e.stopPropagation()}
			onkeydown={(e) => { if (e.key === 'Escape') closeDeleteModal(); }}
		>
			<header class="modal-header modal-header-danger">
				<h2 id="delete-modal-title">Supprimer la classe</h2>
				<button class="modal-close" onclick={closeDeleteModal} aria-label="Fermer">×</button>
			</header>

			<div class="modal-body">
				<p id="delete-modal-description">
					Êtes-vous sûr de vouloir supprimer la classe <strong>{classToDelete.name}</strong> ?
				</p>
				<p class="delete-warning">Cette action est irréversible.</p>
			</div>

			<div class="modal-actions">
				<button type="button" class="btn-secondary" onclick={closeDeleteModal} disabled={isDeleting}>
					Annuler
				</button>
				<button type="button" class="btn-danger" onclick={handleConfirmDelete} disabled={isDeleting}>
					{#if isDeleting}
						Suppression...
					{:else}
						Supprimer
					{/if}
				</button>
			</div>
		</div>
	</div>
{/if}

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

	.page-header {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		gap: 1rem;
		margin-bottom: 1.5rem;
		flex-wrap: wrap;
	}

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

	.subtitle {
		margin: 0.25rem 0 0;
		color: #6b7280;
		font-size: 0.875rem;
	}

	.btn-primary {
		display: inline-flex;
		align-items: center;
		gap: 0.5rem;
		padding: 0.75rem 1.25rem;
		background: #3b82f6;
		color: white;
		border: none;
		border-radius: 0.5rem;
		font-weight: 600;
		cursor: pointer;
		transition: background 0.2s;
	}

	.btn-primary:hover:not(:disabled) {
		background: #2563eb;
	}

	.btn-primary:disabled {
		opacity: 0.6;
		cursor: not-allowed;
	}

	.btn-secondary {
		padding: 0.5rem 1rem;
		background: white;
		color: #374151;
		border: 1px solid #d1d5db;
		border-radius: 0.375rem;
		font-weight: 500;
		cursor: pointer;
		transition: all 0.2s;
	}

	.btn-secondary:hover:not(:disabled) {
		background: #f3f4f6;
	}

	.btn-danger {
		padding: 0.5rem 1rem;
		background: #fef2f2;
		color: #dc2626;
		border: 1px solid #fecaca;
		border-radius: 0.375rem;
		font-weight: 500;
		cursor: pointer;
		transition: all 0.2s;
	}

	.btn-danger:hover {
		background: #fee2e2;
	}

	.btn-sm {
		padding: 0.375rem 0.75rem;
		font-size: 0.875rem;
	}

	.btn-icon {
		font-size: 1.25rem;
		line-height: 1;
	}

	.alert {
		display: flex;
		align-items: center;
		gap: 0.75rem;
		padding: 1rem;
		border-radius: 0.5rem;
		margin-bottom: 1rem;
	}

	.alert-error {
		background: #fef2f2;
		border: 1px solid #fecaca;
		color: #dc2626;
	}

	.alert-icon {
		flex-shrink: 0;
	}

	.alert-close {
		margin-left: auto;
		padding: 0.25rem 0.5rem;
		background: none;
		border: none;
		font-size: 1.25rem;
		cursor: pointer;
		opacity: 0.6;
	}

	.alert-close:hover {
		opacity: 1;
	}

	.loading-state,
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 3rem;
		text-align: center;
		background: white;
		border-radius: 0.75rem;
		border: 2px dashed #e5e7eb;
	}

	.spinner {
		width: 2rem;
		height: 2rem;
		border: 3px solid #e5e7eb;
		border-top-color: #3b82f6;
		border-radius: 50%;
		animation: spin 0.8s linear infinite;
	}

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

	.empty-icon {
		font-size: 3rem;
		margin-bottom: 1rem;
	}

	.empty-state h2 {
		margin: 0 0 0.5rem;
		font-size: 1.25rem;
		color: #1f2937;
	}

	.empty-state p {
		margin: 0 0 1.5rem;
		color: #6b7280;
	}

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

	.class-card {
		display: flex;
		flex-direction: column;
		gap: 1rem;
		padding: 1.25rem;
		background: white;
		border: 1px solid #e5e7eb;
		border-radius: 0.75rem;
		transition: box-shadow 0.2s;
	}

	.class-card:hover {
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
	}

	.class-info {
		display: flex;
		align-items: center;
		gap: 0.75rem;
	}

	.class-name {
		margin: 0;
		font-size: 1.125rem;
		font-weight: 600;
		color: #1f2937;
	}

	.class-level {
		padding: 0.25rem 0.5rem;
		background: #eff6ff;
		color: #3b82f6;
		border-radius: 0.25rem;
		font-size: 0.75rem;
		font-weight: 500;
	}

	.class-meta {
		display: flex;
		gap: 1rem;
		flex-wrap: wrap;
	}

	.meta-item {
		display: flex;
		align-items: center;
		gap: 0.25rem;
		font-size: 0.875rem;
		color: #6b7280;
	}

	.meta-icon {
		font-size: 0.875rem;
	}

	.status-active {
		color: #059669;
	}

	.status-archived {
		color: #6b7280;
	}

	.class-actions {
		display: flex;
		gap: 0.5rem;
		margin-top: auto;
	}

	/* Modal */
	.modal-overlay {
		position: fixed;
		inset: 0;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 1rem;
		z-index: 100;
	}

	.modal {
		background: white;
		border-radius: 0.75rem;
		width: 100%;
		max-width: 28rem;
		max-height: 90vh;
		overflow: auto;
		box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
	}

	.modal-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 1.25rem 1.5rem;
		border-bottom: 1px solid #e5e7eb;
	}

	.modal-header h2 {
		margin: 0;
		font-size: 1.125rem;
		font-weight: 600;
		color: #1f2937;
	}

	.modal-close {
		padding: 0.25rem 0.5rem;
		background: none;
		border: none;
		font-size: 1.5rem;
		line-height: 1;
		color: #6b7280;
		cursor: pointer;
	}

	.modal-close:hover {
		color: #1f2937;
	}

	.modal-body {
		padding: 1.5rem;
	}

	.form-group {
		margin-bottom: 1.25rem;
	}

	.form-group label {
		display: block;
		margin-bottom: 0.5rem;
		font-weight: 500;
		color: #374151;
	}

	.form-group input,
	.form-group select {
		width: 100%;
		padding: 0.75rem 1rem;
		border: 1px solid #d1d5db;
		border-radius: 0.375rem;
		font-size: 1rem;
		transition: border-color 0.2s;
	}

	.form-group input:focus,
	.form-group select:focus {
		outline: none;
		border-color: #3b82f6;
		box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
	}

	.modal-actions {
		display: flex;
		justify-content: flex-end;
		gap: 0.75rem;
		padding-top: 1rem;
		border-top: 1px solid #e5e7eb;
	}

	/* Delete confirmation modal */
	.modal-confirm {
		max-width: 24rem;
	}

	.modal-confirm .modal-actions {
		padding: 1rem 1.5rem;
		border-top: 1px solid #e5e7eb;
	}

	.modal-header-danger {
		background: #fef2f2;
		border-bottom-color: #fecaca;
	}

	.modal-header-danger h2 {
		color: #dc2626;
	}

	.delete-warning {
		margin: 0.75rem 0 0;
		font-size: 0.875rem;
		color: #6b7280;
	}
</style>
