<script lang="ts">
	import { onMount } from 'svelte';
	import { authStore } from '$lib/stores/auth.svelte.js';
	import { api, type Feedback, type Grade } from '$lib/api';
	import { goto } from '$app/navigation';

	let feedbackList = $state<Feedback[]>([]);
	let studentGrades = $state<Grade[]>([]);
	let isLoading = $state(true);
	let error = $state<string | null>(null);

	onMount(async () => {
		if (!authStore.isAuthenticated) {
			goto('/login');
			return;
		}

		if (authStore.isTeacher) {
			await loadFeedback();
		} else {
			await loadStudentGrades();
		}

		isLoading = false;
	});

	async function loadFeedback() {
		const response = await api.getFeedback();

		if (response.data) {
			feedbackList = response.data;
		} else {
			error = response.error || 'Fehler beim Laden des Feedbacks';
		}
	}

	async function loadStudentGrades() {
		const response = await api.getGrades();

		if (response.data) {
			// Sortiere nach Datum (neueste zuerst)
			studentGrades = response.data.sort((a, b) =>
				new Date(b.date).getTime() - new Date(a.date).getTime()
			);
		} else {
			error = response.error || 'Fehler beim Laden der Noten';
		}
	}

	function formatDate(dateString: string): string {
		return new Date(dateString).toLocaleDateString('de-DE', {
			day: '2-digit',
			month: '2-digit',
			year: 'numeric'
		});
	}

	function formatDateTime(dateString: string): string {
		return new Date(dateString).toLocaleDateString('de-DE', {
			day: '2-digit',
			month: '2-digit',
			year: 'numeric',
			hour: '2-digit',
			minute: '2-digit'
		});
	}

	function getGradeColor(grade: number): string {
		if (grade <= 2.0) return '#4caf50'; // Grün
		if (grade <= 3.0) return '#ff9800'; // Orange
		if (grade <= 4.0) return '#ff5722'; // Orange-Rot
		return '#f44336'; // Rot
	}
</script>

<div class="feedback-page">
	<div class="content">
		<div class="header-section">
			<h2>{authStore.isTeacher ? 'Feedback' : 'Noten'}</h2>
			<p class="subtitle">
				{#if authStore.isTeacher}
					Übersicht über alle eingegangenen Feedbacks
				{:else}
					Ihre Noten im Überblick
				{/if}
			</p>
		</div>

		{#if error}
			<div class="error-banner">
				{error}
				<button onclick={() => (error = null)} class="close-btn">×</button>
			</div>
		{/if}

		{#if isLoading}
			<div class="loading-state">
				<p>Lädt...</p>
			</div>
		{:else if authStore.isTeacher}
			<!-- Lehrer Ansicht -->
			<div class="feedback-container">
				{#if feedbackList.length === 0}
					<div class="empty-state">
						<p>Noch kein Feedback vorhanden</p>
					</div>
				{:else}
					<div class="feedback-grid">
						{#each feedbackList as feedback}
							<div class="feedback-card">
								<div class="feedback-header">
									<h3>{feedback.timetableEntry?.subject.name || 'Unbekanntes Fach'}</h3>
									{#if feedback.isAnonymous}
										<span class="badge anonymous">Anonym</span>
									{:else}
										<span class="badge student">Von: {feedback.student?.username || 'N/A'}</span>
									{/if}
								</div>

								<div class="rating-section">
									<div class="rating-display">
										<span class="rating-value">{feedback.overallRating}</span>
										<span class="rating-max">/10</span>
										<span class="stars">{'⭐'.repeat(feedback.overallRating)}</span>
									</div>
									<span class="rating-label">Gesamtbewertung</span>
								</div>

								<div class="feedback-content">
									{#if feedback.whatWasGood}
										<div class="feedback-section">
											<h4>✅ Was war gut:</h4>
											<p>{feedback.whatWasGood}</p>
										</div>
									{/if}

									{#if feedback.whatCanImprove}
										<div class="feedback-section">
											<h4>💡 Verbesserungsvorschläge:</h4>
											<p>{feedback.whatCanImprove}</p>
										</div>
									{/if}

									{#if feedback.additionalComments}
										<div class="feedback-section">
											<h4>💬 Zusätzliche Anmerkungen:</h4>
											<p>{feedback.additionalComments}</p>
										</div>
									{/if}
								</div>

								<div class="feedback-footer">
									<span class="date">{formatDateTime(feedback.createdAt || '')}</span>
								</div>
							</div>
						{/each}
					</div>
				{/if}
			</div>
		{:else}
			<!-- Schüler Ansicht - Noten -->
			<div class="grades-container">
				{#if studentGrades.length === 0}
					<div class="empty-state">
						<p>Noch keine Noten vorhanden</p>
					</div>
				{:else}
					<div class="grades-list">
						{#each studentGrades as grade}
							<div class="grade-card">
								<div class="grade-header">
									<div class="grade-subject-info">
										<h3>{grade.timetableEntry?.subject.name || 'Unbekanntes Fach'}</h3>
										<p class="grade-teacher">Lehrer: {grade.timetableEntry?.teacher?.username || 'N/A'}</p>
									</div>
									<div class="grade-value" style="background-color: {getGradeColor(grade.grade)}">
										{grade.grade.toFixed(1)}
									</div>
								</div>

								<div class="grade-details">
									<div class="grade-info-row">
										<span class="grade-label">Art:</span>
										<span class="grade-info">{grade.gradeType}</span>
									</div>

									{#if grade.title}
										<div class="grade-info-row">
											<span class="grade-label">Titel:</span>
											<span class="grade-info">{grade.title}</span>
										</div>
									{/if}

									{#if grade.description}
										<div class="grade-info-row">
											<span class="grade-label">Beschreibung:</span>
											<span class="grade-info">{grade.description}</span>
										</div>
									{/if}

									{#if grade.achievedPoints && grade.maxPoints}
										<div class="grade-info-row">
											<span class="grade-label">Punkte:</span>
											<span class="grade-info">{grade.achievedPoints} / {grade.maxPoints}</span>
										</div>
									{/if}

									{#if grade.weight && grade.weight !== 1}
										<div class="grade-info-row">
											<span class="grade-label">Gewichtung:</span>
											<span class="grade-info">{grade.weight}x</span>
										</div>
									{/if}
								</div>

								<div class="grade-footer">
									<span class="grade-date">{formatDate(grade.date)}</span>
								</div>
							</div>
						{/each}
					</div>
				{/if}
			</div>
		{/if}
	</div>
</div>

<style>
	.feedback-page {
		min-height: 100vh;
		background: #f5f7fa;
	}

	.content {
		max-width: 1200px;
		margin: 0 auto;
		padding: 2rem;
	}

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

	.header-section h2 {
		margin: 0 0 0.5rem;
		color: #333;
		font-size: 2rem;
	}

	.subtitle {
		color: #666;
		margin: 0;
	}

	.error-banner {
		background: #fee;
		color: #c33;
		padding: 1rem 1.25rem;
		border-radius: 8px;
		margin-bottom: 1.5rem;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.close-btn {
		background: none;
		border: none;
		color: inherit;
		font-size: 1.5rem;
		cursor: pointer;
		padding: 0;
		line-height: 1;
	}

	.loading-state,
	.empty-state {
		text-align: center;
		padding: 3rem;
		background: white;
		border-radius: 12px;
		color: #999;
	}

	/* Lehrer - Feedback Container */
	.feedback-container {
		background: white;
		border-radius: 12px;
		padding: 2rem;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
	}

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

	.feedback-card {
		background: #f9f9f9;
		border-radius: 12px;
		padding: 1.5rem;
		border-left: 4px solid #667eea;
		transition: transform 0.2s, box-shadow 0.2s;
	}

	.feedback-card:hover {
		transform: translateY(-2px);
		box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
	}

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

	.feedback-header h3 {
		margin: 0;
		color: #333;
		font-size: 1.25rem;
	}

	.badge {
		display: inline-block;
		padding: 0.25rem 0.75rem;
		border-radius: 20px;
		font-size: 0.75rem;
		font-weight: 600;
		white-space: nowrap;
	}

	.badge.anonymous {
		background: #ff9800;
		color: white;
	}

	.badge.student {
		background: #2196f3;
		color: white;
	}

	.rating-section {
		background: white;
		padding: 1rem;
		border-radius: 8px;
		text-align: center;
		margin-bottom: 1rem;
	}

	.rating-display {
		display: flex;
		align-items: baseline;
		justify-content: center;
		gap: 0.5rem;
		margin-bottom: 0.5rem;
	}

	.rating-value {
		font-size: 2rem;
		font-weight: 700;
		color: #667eea;
	}

	.rating-max {
		font-size: 1.25rem;
		color: #999;
	}

	.stars {
		font-size: 1.25rem;
	}

	.rating-label {
		display: block;
		font-size: 0.85rem;
		color: #666;
	}

	.feedback-content {
		display: flex;
		flex-direction: column;
		gap: 1rem;
	}

	.feedback-section h4 {
		margin: 0 0 0.5rem;
		font-size: 0.95rem;
		color: #555;
	}

	.feedback-section p {
		margin: 0;
		color: #333;
		line-height: 1.6;
	}

	.feedback-footer {
		margin-top: 1rem;
		padding-top: 1rem;
		border-top: 1px solid #e0e0e0;
	}

	.date {
		font-size: 0.85rem;
		color: #999;
	}

	/* Schüler - Noten Container */
	.grades-container {
		background: white;
		border-radius: 12px;
		padding: 2rem;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
	}

	.grades-list {
		display: flex;
		flex-direction: column;
		gap: 1rem;
	}

	.grade-card {
		background: #f9f9f9;
		border-radius: 12px;
		padding: 1.5rem;
		border-left: 4px solid #667eea;
		transition: transform 0.2s, box-shadow 0.2s;
	}

	.grade-card:hover {
		transform: translateY(-2px);
		box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
	}

	.grade-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 1rem;
		gap: 1rem;
	}

	.grade-subject-info h3 {
		margin: 0 0 0.25rem;
		color: #333;
		font-size: 1.25rem;
	}

	.grade-teacher {
		margin: 0;
		color: #666;
		font-size: 0.9rem;
	}

	.grade-value {
		min-width: 70px;
		height: 70px;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 12px;
		color: white;
		font-size: 1.75rem;
		font-weight: 700;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
	}

	.grade-details {
		display: flex;
		flex-direction: column;
		gap: 0.5rem;
		padding: 1rem;
		background: white;
		border-radius: 8px;
		margin-bottom: 1rem;
	}

	.grade-info-row {
		display: flex;
		gap: 0.5rem;
	}

	.grade-label {
		font-weight: 600;
		color: #555;
		min-width: 120px;
	}

	.grade-info {
		color: #333;
		flex: 1;
	}

	.grade-footer {
		display: flex;
		justify-content: flex-end;
		padding-top: 0.75rem;
		border-top: 1px solid #e0e0e0;
	}

	.grade-date {
		font-size: 0.85rem;
		color: #999;
		font-weight: 500;
	}

	@media (max-width: 768px) {
		.content {
			padding: 1rem;
		}

		.header-section h2 {
			font-size: 1.5rem;
		}

		.feedback-grid {
			grid-template-columns: 1fr;
		}

		.grade-header {
			flex-direction: column;
			align-items: flex-start;
		}

		.grade-value {
			align-self: flex-end;
		}

		.grade-label {
			min-width: 100px;
		}
	}
</style>
