<script lang="ts">
	import { onMount, onDestroy } from 'svelte';
	import { authStore } from '$lib/stores/auth.svelte.js';
	import { classroomStore } from '$lib/stores/classroom.svelte.js';
	import { api, type TimetableEntry } from '$lib/api';
	import AttendanceList from '$lib/components/dashboard/AttendanceList.svelte';
	import { goto } from '$app/navigation';
	import { 
		Mic, 
		Hand, 
		Dices, 
		ArrowDown, 
		Calendar, 
		BookOpen, 
		Zap, 
		BarChart3, 
		ClipboardList, 
		MessageCircle, 
		Palette, 
		Users, 
		GraduationCap, 
		HelpCircle 
	} from 'lucide-svelte';

	let timetableEntries = $state<TimetableEntry[]>([]);
	let isLoading = $state(true);
	let error = $state<string | null>(null);

	const DAYS = ['Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag'];

	let initialized = false;

	$effect(() => {
		if (!authStore.isLoading && !initialized) {
			initialized = true;
			if (!authStore.isAuthenticated) {
				goto('/login');
			} else {
				loadTimetable();
				classroomStore.connect();
			}
		}
	});

	onDestroy(() => {
		classroomStore.disconnect();
	});

	async function loadTimetable() {
		isLoading = true;
		error = null;

		const response = await api.getTimetable();

		if (response.data) {
			timetableEntries = response.data.slice(0, 5); // Nur die nächsten 5 Einträge
		} else {
			error = response.error || 'Fehler beim Laden des Stundenplans';
		}

		isLoading = false;
	}

	function getTodayEntries(): TimetableEntry[] {
		const today = new Date().getDay(); // 0 = Sonntag, 1 = Montag, ...
		const adjustedDay = today === 0 ? 7 : today; // Sonntag auf 7 setzen

		if (adjustedDay > 5) {
			return []; // Wochenende
		}

		return timetableEntries.filter((entry) => entry.dayOfWeek === adjustedDay);
	}
</script>

<div class="dashboard">
	<div class="content">
		<div class="welcome-section">
			<h2>Willkommen, {authStore.user?.username}!</h2>
			<span class="badge badge-primary">{authStore.user?.role}</span>
		</div>

		{#if classroomStore.activeStudent}
			<div class="active-student-banner">
				<div class="active-content">
					<span class="active-icon"><Mic size={24} /></span>
					<span class="active-label">Aktuell dran:</span>
					<span class="active-name">{classroomStore.activeStudent.username}</span>
				</div>
				{#if authStore.isTeacher}
					<button class="btn btn-secondary btn-sm" onclick={() => classroomStore.resetActive()}>Beenden</button>
				{:else if authStore.user?.id === classroomStore.activeStudent.userId}
					<button class="btn btn-secondary btn-sm" onclick={() => classroomStore.endTurn()}>Fertig</button>
				{/if}
			</div>
		{/if}

		<div class="dashboard-grid">
			<!-- Virtuelles Klassenzimmer Card -->
			<div class="card classroom-card">
				<div class="card-header">
					<h3>Virtuelles Klassenzimmer</h3>
					<span class="icon"><Hand size={24} /></span>
				</div>
				<div class="card-body">
					{#if authStore.isTeacher}
						<div class="teacher-controls">
							<div class="control-row">
								<button 
									class="btn btn-primary" 
									onclick={() => classroomStore.pickRandom()} 
									disabled={classroomStore.raisedHands.length === 0}
								>
									<Dices size={18} /> Zufall
								</button>
								<button 
									class="btn btn-secondary" 
									onclick={() => classroomStore.lowerAllHands()} 
									disabled={classroomStore.raisedHands.length === 0}
								>
									<ArrowDown size={18} /> Alle senken
								</button>
							</div>
							
							<h4 class="section-title">Meldungen ({classroomStore.raisedHands.length})</h4>
							
							{#if classroomStore.raisedHands.length === 0}
								<p class="text-muted">Keine Meldungen</p>
							{:else}
								<ul class="raised-list">
									{#each classroomStore.raisedHands as hand}
										<li class="raised-item">
											<div class="student-info">
												<span class="hand-icon">
													{#if hand.type === 'normal'}
														<Hand size={20} />
													{:else}
														<HelpCircle size={20} />
													{/if}
												</span>
												<span class="student-name">{hand.username}</span>
												<span class="badge badge-default">{new Date(hand.raisedAt).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}</span>
											</div>
											<button class="btn btn-primary btn-sm" onclick={() => classroomStore.pickStudent(hand.userId)}>
												Wählen
											</button>
										</li>
									{/each}
								</ul>
							{/if}
						</div>
					{:else}
						<!-- Student View -->
						<div class="student-controls">
							{#if classroomStore.myHand}
								<div class="status-message">
									<span class="status-icon large">
										{#if classroomStore.myHand.type === 'normal'}
											<Hand size={48} />
										{:else}
											<HelpCircle size={48} />
										{/if}
									</span>
									<p>Du meldest dich ({classroomStore.myHand.type === 'normal' ? 'Normal' : 'Frage'})</p>
									<button class="btn btn-secondary w-full" onclick={() => classroomStore.lowerHand()}>
										Hand senken
									</button>
								</div>
							{:else}
								<p class="instruction">Möchtest du etwas sagen?</p>
								<div class="button-grid">
									<button class="btn btn-primary raise-btn" onclick={() => classroomStore.raiseHand('normal')}>
										<span class="btn-icon"><Hand size={32} /></span>
										<span>Melden</span>
									</button>
									<button class="btn btn-secondary raise-btn" onclick={() => classroomStore.raiseHand('question')}>
										<span class="btn-icon"><HelpCircle size={32} /></span>
										<span>Frage</span>
									</button>
								</div>
							{/if}
						</div>
					{/if}
				</div>
			</div>

			{#if authStore.isTeacher}
				<AttendanceList />
			{/if}

			<div class="card">
				<div class="card-header">
					<h3>Heutige Veranstaltungen</h3>
					<span class="icon"><Calendar size={24} /></span>
				</div>
				<div class="card-body">
					{#if isLoading}
						<div class="text-center p-md">
							<span class="loading-spinner"></span>
						</div>
					{:else if error}
						<div class="alert alert-error">{error}</div>
					{:else}
						{#each getTodayEntries() as entry}
							<div class="event-item">
								<div class="event-time">{entry.startTime} - {entry.endTime}</div>
								<div class="event-details">
									<div class="event-subject">{entry.subject.name}</div>
									{#if entry.teacher}
										<div class="event-teacher">{entry.teacher.username}</div>
									{/if}
									{#if entry.room}
										<div class="event-room">Raum: {entry.room.number}</div>
									{/if}
								</div>
							</div>
						{:else}
							<p class="text-muted text-center">Heute keine Veranstaltungen</p>
						{/each}
					{/if}
				</div>
			</div>

			<div class="card">
				<div class="card-header">
					<h3>Kommende Veranstaltungen</h3>
					<span class="icon"><BookOpen size={24} /></span>
				</div>
				<div class="card-body">
					{#if isLoading}
						<div class="text-center p-md">
							<span class="loading-spinner"></span>
						</div>
					{:else if error}
						<div class="alert alert-error">{error}</div>
					{:else}
						{#each timetableEntries as entry}
							<div class="event-item">
								<div class="event-time">
									{DAYS[entry.dayOfWeek - 1]}, {entry.startTime}
								</div>
								<div class="event-details">
									<div class="event-subject">{entry.subject.name}</div>
									{#if entry.room}
										<div class="event-room">Raum: {entry.room.number}</div>
									{/if}
								</div>
							</div>
						{:else}
							<p class="text-muted text-center">Keine kommenden Veranstaltungen</p>
						{/each}
					{/if}
				</div>
			</div>

			{#if authStore.isTeacher}
				<div class="card">
					<div class="card-header">
						<h3>Lehrer-Funktionen</h3>
						<span class="icon"><GraduationCap size={24} /></span>
					</div>
					<div class="card-body">
						<p>Als Lehrer haben Sie Zugriff auf:</p>
						<ul class="feature-list">
							<li>Vollständige Nutzerverwaltung</li>
							<li>Notenverwaltung mit Gewichtung</li>
							<li>Alle Stundenpläne einsehen</li>
							<li>Benutzer erstellen und bearbeiten</li>
						</ul>
					</div>
				</div>
			{/if}
		</div>
	</div>
</div>

<style>
	.dashboard {
		min-height: 100vh;
		background: var(--bg-secondary);
	}

	.content {
		max-width: 1200px;
		margin: 0 auto;
		padding: var(--space-xl);
	}

	.welcome-section {
		margin-bottom: var(--space-xl);
		display: flex;
		align-items: center;
		gap: var(--space-md);
		flex-wrap: wrap;
	}

	.welcome-section h2 {
		margin: 0;
		font-family: var(--font-heading);
		font-size: var(--text-3xl);
	}

	/* Active Student Banner */
	.active-student-banner {
		background: var(--primary-500);
		color: white;
		padding: var(--space-md) var(--space-lg);
		border-radius: var(--radius-md);
		margin-bottom: var(--space-xl);
		display: flex;
		justify-content: space-between;
		align-items: center;
		animation: slideDown 0.3s ease-out;
	}

	@keyframes slideDown {
		from { transform: translateY(-20px); opacity: 0; }
		to { transform: translateY(0); opacity: 1; }
	}

	.active-content {
		display: flex;
		align-items: center;
		gap: var(--space-md);
	}

	.active-icon {
		font-size: 1.5rem;
		background: rgba(255, 255, 255, 0.2);
		width: 40px;
		height: 40px;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
	}

	.active-label {
		font-weight: var(--font-medium);
		opacity: 0.9;
	}

	.active-name {
		font-weight: var(--font-bold);
		font-size: var(--text-lg);
	}

	/* Use global dashboard-grid from app.css/design system if available, 
	   but locally defined here to ensure it matches the layout needs */
	.dashboard-grid {
		display: grid;
		grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
		gap: var(--space-lg);
	}

	.classroom-card {
		grid-column: 1 / -1; 
	}
	
	@media (min-width: 1024px) {
		.classroom-card {
			grid-column: span 2;
		}
	}

	.card-header {
		padding-bottom: var(--space-md);
		margin-bottom: var(--space-md);
		border-bottom: 1px solid var(--neutral-200);
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.card-header h3 {
		margin: 0;
		font-size: var(--text-lg);
	}

	.icon {
		font-size: 1.5rem;
	}

	/* Classroom Styles */
	.control-row {
		display: flex;
		gap: var(--space-md);
		margin-bottom: var(--space-lg);
	}

	.section-title {
		margin: 0 0 var(--space-md) 0;
		font-size: var(--text-sm);
		color: var(--neutral-600);
		text-transform: uppercase;
		letter-spacing: 0.5px;
	}

	.raised-list {
		list-style: none;
		padding: 0;
		margin: 0;
		display: flex;
		flex-direction: column;
		gap: var(--space-sm);
	}

	.raised-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: var(--space-sm);
		background: var(--neutral-50);
		border-radius: var(--radius-sm);
		border-left: 3px solid var(--warning-500);
	}

	.student-info {
		display: flex;
		align-items: center;
		gap: var(--space-sm);
	}

	.hand-icon {
		font-size: 1.2rem;
	}

	.student-name {
		font-weight: var(--font-semibold);
		color: var(--neutral-900);
	}

	/* Student Controls */
	.student-controls {
		text-align: center;
		padding: var(--space-md) 0;
	}

	.instruction {
		margin-bottom: var(--space-lg);
		color: var(--neutral-600);
	}

	.button-grid {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: var(--space-md);
	}

	.raise-btn {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		gap: var(--space-sm);
		padding: var(--space-lg);
		height: auto;
	}

	.btn-icon {
		font-size: 2rem;
	}

	.status-message {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: var(--space-md);
	}

	.status-icon.large {
		font-size: 3rem;
		animation: wave 2s infinite;
	}

	@keyframes wave {
		0%, 100% { transform: rotate(0deg); }
		25% { transform: rotate(-10deg); }
		75% { transform: rotate(10deg); }
	}

	.event-item {
		padding: var(--space-sm);
		border-left: 3px solid var(--primary-500);
		background: var(--neutral-50);
		border-radius: var(--radius-sm);
		margin-bottom: var(--space-sm);
	}

	.event-item:last-child {
		margin-bottom: 0;
	}

	.event-time {
		font-weight: var(--font-semibold);
		color: var(--primary-500);
		font-size: var(--text-sm);
		margin-bottom: var(--space-xs);
	}

	.event-subject {
		font-weight: var(--font-semibold);
		color: var(--neutral-900);
		margin-bottom: var(--space-xs);
	}

	.event-teacher,
	.event-room {
		font-size: var(--text-sm);
		color: var(--neutral-600);
	}

	.quick-actions {
		display: flex;
		flex-direction: column;
		gap: var(--space-sm);
	}

	.action-btn {
		display: flex;
		align-items: center;
		gap: var(--space-md);
		padding: var(--space-sm) var(--space-md);
		background: var(--neutral-50);
		border: 1px solid var(--neutral-200);
		border-radius: var(--radius-md);
		text-decoration: none;
		color: var(--neutral-900);
		font-weight: var(--font-medium);
		transition: background var(--transition-fast), border-color var(--transition-fast);
		cursor: pointer;
		font-family: inherit;
		font-size: var(--text-base);
	}

	.action-btn:hover {
		background: white;
		border-color: var(--primary-500);
		color: var(--primary-500);
	}

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

	.feature-list {
		margin: var(--space-md) 0 0;
		padding-left: var(--space-lg);
		color: var(--neutral-600);
	}

	.feature-list li {
		margin-bottom: var(--space-sm);
	}

	@media (max-width: 768px) {
		.content {
			padding: var(--space-md);
		}

		.welcome-section h2 {
			font-size: var(--text-2xl);
		}

		.dashboard-grid {
			grid-template-columns: 1fr;
		}
	}
</style>
