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

	let subjects = $state<TeacherGradesOverview[]>([]);
	let selectedSubject = $state<SubjectGradeDetailsByName | null>(null);
	let loading = $state(true);
	let error = $state<string | null>(null);

	// State für die dynamische Gewichtungsanpassung
	let editingGradeId = $state<number | null>(null);
	let editingWeight = $state<number>(1.0);

	// Hilfsfunktion für deutsche Wochentage
	function getDayName(day: number): string {
		const days = ['Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag'];
		return days[day - 1] || 'Unbekannt';
	}

	// Hilfsfunktion für Notennamen (1.0 = Sehr gut, 6.0 = Ungenügend)
	function getGradeName(grade: number): string {
		if (grade >= 1.0 && grade < 1.5) return 'Sehr gut';
		if (grade >= 1.5 && grade < 2.5) return 'Gut';
		if (grade >= 2.5 && grade < 3.5) return 'Befriedigend';
		if (grade >= 3.5 && grade < 4.5) return 'Ausreichend';
		if (grade >= 4.5 && grade < 5.5) return 'Mangelhaft';
		return 'Ungenügend';
	}

	// Hilfsfunktion für Notenfarben
	function getGradeColor(grade: number | null): string {
		if (grade === null) return 'grade-none';
		if (grade >= 1.0 && grade < 1.5) return 'grade-excellent';
		if (grade >= 1.5 && grade < 2.5) return 'grade-good';
		if (grade >= 2.5 && grade < 3.5) return 'grade-satisfactory';
		if (grade >= 3.5 && grade < 4.5) return 'grade-sufficient';
		if (grade >= 4.5 && grade < 5.5) return 'grade-poor';
		return 'grade-fail';
	}

	// Daten laden
	async function loadOverview() {
		loading = true;
		error = null;
		const response = await api.getTeacherGradesOverview();

		if (response.error) {
			error = response.error;
		} else if (response.data) {
			subjects = response.data;
		}
		loading = false;
	}

	// Detaillierte Ansicht eines Fachs laden (nach Fachname, um alle Stundenplan-Einträge zu erfassen)
	async function loadSubjectDetails(subjectName: string) {
		loading = true;
		error = null;
		const response = await api.getSubjectGradeDetailsByName(subjectName);

		if (response.error) {
			error = response.error;
		} else if (response.data) {
			selectedSubject = response.data;
		}
		loading = false;
	}

	// Zurück zur Übersicht
	function backToOverview() {
		selectedSubject = null;
		loadOverview();
	}

	// Gewichtung bearbeiten starten
	function startEditWeight(gradeId: number, currentWeight: number) {
		editingGradeId = gradeId;
		editingWeight = currentWeight;
	}

	// Gewichtung speichern mit dynamischer Anpassung
	async function saveWeight(gradeId: number, studentId: number) {
		if (!selectedSubject) return;

		// Alte Gewichtung finden
		let oldWeight = 1.0;
		let allStudentGrades: GradeDetail[] = [];

		for (const student of selectedSubject.students) {
			if (student.student.id === studentId) {
				const grade = student.grades.find(g => g.id === gradeId);
				if (grade) {
					oldWeight = grade.weight;
					allStudentGrades = student.grades;
				}
				break;
			}
		}

		// Gewichtung aktualisieren
		const response = await api.updateGrade(gradeId, {
			weight: editingWeight
		});

		if (response.error) {
			error = response.error;
			editingGradeId = null;
			return;
		}

		// Dynamische Anpassung der anderen Gewichtungen
		const weightDiff = editingWeight - oldWeight;
		const otherGrades = allStudentGrades.filter(g => g.id !== gradeId);

		if (otherGrades.length > 0 && Math.abs(weightDiff) > 0.01) {
			const totalOtherWeight = otherGrades.reduce((sum, g) => sum + g.weight, 0);
			const adjustmentFactor = totalOtherWeight > 0
				? (totalOtherWeight - weightDiff) / totalOtherWeight
				: 1.0;

			for (const otherGrade of otherGrades) {
				const newWeight = Math.max(0.1, otherGrade.weight * adjustmentFactor);
				await api.updateGrade(otherGrade.id, {
					weight: Number(newWeight.toFixed(2))
				});
			}
		}

		editingGradeId = null;

		if (selectedSubject) {
			await loadSubjectDetails(selectedSubject.subject.name);
		}
	}

	// Gewichtung bearbeiten abbrechen
	function cancelEditWeight() {
		editingGradeId = null;
	}

	// Note löschen
	async function deleteGrade(gradeId: number) {
		if (!confirm('Möchten Sie diese Note wirklich löschen?')) return;

		const response = await api.deleteGrade(gradeId);

		if (response.error) {
			error = response.error;
		} else {
			if (selectedSubject) {
				await loadSubjectDetails(selectedSubject.subject.name);
			}
		}
	}

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

	onMount(() => {
		if (!authStore.isTeacher) {
			goto('/dashboard');
			return;
		}

		loadOverview();
	});
</script>

<div class="grades-page">
	<div class="content">
		<div class="header-section">
			{#if selectedSubject}
				<button onclick={backToOverview} class="back-btn">
					← Zurück zur Übersicht
				</button>
			{/if}
			<h2>Notenverwaltung</h2>
			<p class="subtitle">
				{#if selectedSubject}
					Detailansicht: {selectedSubject.subject.name}
				{:else}
					Übersicht aller Fächer und vergebenen Noten
				{/if}
			</p>
		</div>

		{#if loading}
			<div class="loading-container">
				<div class="spinner"></div>
				<p>Lade Noten...</p>
			</div>
		{:else if error}
			<div class="error-message">
				<span class="error-icon">⚠️</span>
				<span>Fehler: {error}</span>
			</div>
		{:else if selectedSubject}
			<!-- Detailansicht eines Fachs -->
			<div class="subject-info-card">
				<div class="subject-header">
					<div>
						<h3>{selectedSubject.subject.name}</h3>
						<div class="subject-meta">
							{#if selectedSubject.timetableEntries.length > 1}
								<span><strong>Termine:</strong></span>
								{#each selectedSubject.timetableEntries as entry}
									<span>{getDayName(entry.dayOfWeek)} {entry.startTime}-{entry.endTime}{entry.teacher?.username ? ` (${entry.teacher.username})` : ''}</span>
								{/each}
							{:else if selectedSubject.timetableEntries[0]}
								<span><strong>Lehrer:</strong> {selectedSubject.timetableEntries[0].teacher?.username || 'Nicht angegeben'}</span>
								<span><strong>Tag:</strong> {getDayName(selectedSubject.timetableEntries[0].dayOfWeek)}</span>
								<span><strong>Zeit:</strong> {selectedSubject.timetableEntries[0].startTime} - {selectedSubject.timetableEntries[0].endTime}</span>
							{/if}
						</div>
					</div>
					<div class="subject-stats">
						<div class="stat">
							<div class="stat-value">{selectedSubject.totalStudents}</div>
							<div class="stat-label">Schüler</div>
						</div>
						<div class="stat">
							<div class="stat-value">{selectedSubject.totalGrades}</div>
							<div class="stat-label">Noten</div>
						</div>
					</div>
				</div>
			</div>

			<!-- Schüler-Noten -->
			<div class="students-container">
				{#each selectedSubject.students as studentData}
					<div class="student-card">
						<div class="student-header">
							<div class="student-info">
								<h4>{studentData.student.username}</h4>
								<p class="student-email">{studentData.student.email}</p>
							</div>
							<div class="student-grade-summary">
								<div class="average-label">Gesamtnote</div>
								<div class="average-value {getGradeColor(studentData.average)}">
									{studentData.average !== null ? studentData.average.toFixed(2) : 'N/A'}
								</div>
								{#if studentData.average !== null}
									<div class="average-name {getGradeColor(studentData.average)}">
										{getGradeName(studentData.average)}
									</div>
								{/if}
								<div class="weight-info">
									Gewichtung: {studentData.totalWeight.toFixed(1)}
								</div>
							</div>
						</div>

						<!-- Noten-Tabelle -->
						<div class="grades-table-container">
							<table class="grades-table">
								<thead>
									<tr>
										<th>Datum</th>
										<th>Titel</th>
										<th>Typ</th>
										<th>Note</th>
										<th>Gewichtung</th>
										<th>Punkte</th>
										<th>Aktionen</th>
									</tr>
								</thead>
								<tbody>
									{#each studentData.grades as grade}
										<tr>
											<td class="date-cell">
												{formatDate(grade.date)}
											</td>
											<td class="title-cell">
												<div class="grade-title">{grade.title || '-'}</div>
												{#if grade.description}
													<div class="grade-description">{grade.description}</div>
												{/if}
											</td>
											<td>
												<span class="grade-type-badge">
													{grade.gradeType}
												</span>
											</td>
											<td>
												<span class="grade-value {getGradeColor(grade.grade)}">
													{grade.grade.toFixed(1)}
												</span>
											</td>
											<td class="weight-cell">
												{#if editingGradeId === grade.id}
													<div class="weight-edit">
														<input
															type="number"
															bind:value={editingWeight}
															step="0.1"
															min="0.1"
															max="10"
															class="weight-input"
														/>
														<button
															onclick={() => saveWeight(grade.id, studentData.student.id)}
															class="btn-save"
															title="Speichern"
														>
															✓
														</button>
														<button
															onclick={cancelEditWeight}
															class="btn-cancel"
															title="Abbrechen"
														>
															✗
														</button>
													</div>
												{:else}
													<button
														onclick={() => startEditWeight(grade.id, grade.weight)}
														class="weight-btn"
													>
														{grade.weight.toFixed(1)}x
													</button>
												{/if}
											</td>
											<td class="points-cell">
												{#if grade.maxPoints && grade.achievedPoints !== null && grade.achievedPoints !== undefined}
													{grade.achievedPoints}/{grade.maxPoints}
												{:else}
													-
												{/if}
											</td>
											<td>
												<button
													onclick={() => deleteGrade(grade.id)}
													class="btn-delete"
												>
													Löschen
												</button>
											</td>
										</tr>
									{/each}
								</tbody>
							</table>

							{#if studentData.grades.length === 0}
								<div class="no-data">Keine Noten vorhanden</div>
							{/if}
						</div>
					</div>
				{/each}
			</div>

			{#if selectedSubject.students.length === 0}
				<div class="no-data-card">
					<span class="icon">📝</span>
					<p>Keine Schüler mit Noten in diesem Fach</p>
				</div>
			{/if}
		{:else}
			<!-- Übersicht aller Fächer -->
			<div class="subjects-grid">
				{#each subjects as subject}
					<button
						onclick={() => loadSubjectDetails(subject.subject.name)}
						class="subject-card"
					>
						<div class="subject-card-header">
							<h3>{subject.subject.name}</h3>
							<span class="subject-icon">📚</span>
						</div>

						<div class="subject-details">
							{#if subject.timetableEntries.length > 1}
								<div class="detail-row multiple-entries-info">
									<span class="detail-label">📅 Mehrere Termine:</span>
									<span class="detail-value">{subject.timetableEntries.length}x</span>
								</div>
								{#each subject.timetableEntries as entry}
									<div class="detail-row schedule-entry">
										<span class="detail-label">{getDayName(entry.dayOfWeek)}:</span>
										<span class="detail-value">{entry.startTime}-{entry.endTime}</span>
									</div>
								{/each}
							{:else if subject.timetableEntries[0]}
								<div class="detail-row">
									<span class="detail-label">Lehrer:</span>
									<span class="detail-value">{subject.timetableEntries[0].teacher?.username || 'Nicht angegeben'}</span>
								</div>
								<div class="detail-row">
									<span class="detail-label">Tag:</span>
									<span class="detail-value">{getDayName(subject.timetableEntries[0].dayOfWeek)} {subject.timetableEntries[0].startTime}-{subject.timetableEntries[0].endTime}</span>
								</div>
							{/if}
							<div class="detail-row">
								<span class="detail-label">Schüler:</span>
								<span class="detail-value">{subject.studentCount}</span>
							</div>
							<div class="detail-row">
								<span class="detail-label">Noten:</span>
								<span class="detail-value">{subject.totalGrades}</span>
							</div>
						</div>

						{#if subject.students.length > 0}
							<div class="subject-preview">
								<div class="preview-label">Schüler-Durchschnitt:</div>
								<div class="preview-grades">
									{#each subject.students.slice(0, 4) as student}
										<div class="preview-grade">
											<span class="preview-name">{student.student.username}:</span>
											<span class="preview-value {getGradeColor(student.average)}">
												{student.average !== null ? student.average.toFixed(1) : 'N/A'}
											</span>
										</div>
									{/each}
									{#if subject.students.length > 4}
										<div class="preview-more">
											+{subject.students.length - 4} weitere
										</div>
									{/if}
								</div>
							</div>
						{/if}
					</button>
				{/each}
			</div>

			{#if subjects.length === 0}
				<div class="no-data-card">
					<span class="icon">📚</span>
					<p>Keine Fächer mit Noten vorhanden</p>
				</div>
			{/if}
		{/if}
	</div>
</div>

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

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

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

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

	.subtitle {
		color: #666;
		font-size: 1rem;
		margin: 0;
	}

	.back-btn {
		background: transparent;
		border: none;
		color: #667eea;
		font-weight: 600;
		font-size: 1rem;
		cursor: pointer;
		padding: 0.5rem 0;
		margin-bottom: 0.5rem;
		transition: color 0.2s;
	}

	.back-btn:hover {
		color: #764ba2;
	}

	/* Loading & Error States */
	.loading-container {
		text-align: center;
		padding: 4rem 2rem;
		color: #666;
	}

	.spinner {
		display: inline-block;
		width: 40px;
		height: 40px;
		border: 4px solid #f3f3f3;
		border-top: 4px solid var(--primary);
		border-radius: 50%;
		animation: spin 1s linear infinite;
		margin-bottom: 1rem;
	}

	@keyframes spin {
		0% { transform: rotate(0deg); }
		100% { transform: rotate(360deg); }
	}

	.error-message {
		background: #fee;
		border: 1px solid #fcc;
		color: #c33;
		padding: 1rem;
		border-radius: 8px;
		display: flex;
		align-items: center;
		gap: 0.75rem;
	}

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

	.no-data-card {
		background: white;
		border-radius: 12px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
		padding: 3rem 2rem;
		text-align: center;
		color: #999;
	}

	.no-data-card .icon {
		font-size: 3rem;
		display: block;
		margin-bottom: 1rem;
	}

	/* Subject Info Card */
	.subject-info-card {
		background: white;
		border-radius: 12px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
		padding: 1.5rem;
		margin-bottom: 2rem;
	}

	.subject-header {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		gap: 2rem;
		flex-wrap: wrap;
	}

	.subject-header h3 {
		margin: 0 0 0.75rem 0;
		color: #333;
		font-size: 1.5rem;
	}

	.subject-meta {
		display: flex;
		flex-wrap: wrap;
		gap: 1.5rem;
		color: #666;
		font-size: 0.9rem;
	}

	.subject-stats {
		display: flex;
		gap: 2rem;
	}

	.stat {
		text-align: center;
	}

	.stat-value {
		font-size: 2rem;
		font-weight: bold;
		color: var(--primary);
	}

	.stat-label {
		font-size: 0.85rem;
		color: #666;
		margin-top: 0.25rem;
	}

	/* Students Container */
	.students-container {
		display: flex;
		flex-direction: column;
		gap: 1.5rem;
	}

	/* Student Card */
	.student-card {
		background: white;
		border-radius: 12px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
		overflow: hidden;
		transition: transform 0.2s, box-shadow 0.2s;
	}

	.student-card:hover {
		transform: translateY(-2px);
		box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
	}

	.student-header {
		padding: 1.5rem;
		background: var(--primary);
		color: white;
		display: flex;
		justify-content: space-between;
		align-items: center;
		flex-wrap: wrap;
		gap: 1.5rem;
	}

	.student-info h4 {
		margin: 0 0 0.25rem 0;
		font-size: 1.25rem;
	}

	.student-email {
		margin: 0;
		opacity: 0.9;
		font-size: 0.9rem;
	}

	.student-grade-summary {
		text-align: right;
	}

	.average-label {
		font-size: 0.85rem;
		opacity: 0.9;
		margin-bottom: 0.25rem;
	}

	.average-value {
		font-size: 2.5rem;
		font-weight: bold;
		line-height: 1;
	}

	.average-name {
		font-size: 0.9rem;
		margin-top: 0.25rem;
		font-weight: 600;
	}

	.weight-info {
		font-size: 0.75rem;
		opacity: 0.8;
		margin-top: 0.5rem;
	}

	/* Grades Table */
	.grades-table-container {
		padding: 1.5rem;
	}

	.grades-table {
		width: 100%;
		border-collapse: collapse;
	}

	.grades-table thead th {
		background: #f9f9f9;
		padding: 0.75rem;
		text-align: left;
		font-weight: 600;
		font-size: 0.85rem;
		color: #666;
		text-transform: uppercase;
		letter-spacing: 0.5px;
		border-bottom: 2px solid #e0e0e0;
	}

	.grades-table tbody tr {
		border-bottom: 1px solid #f0f0f0;
		transition: background 0.2s;
	}

	.grades-table tbody tr:hover {
		background: #f9f9f9;
	}

	.grades-table tbody td {
		padding: 1rem 0.75rem;
		font-size: 0.9rem;
		color: #333;
	}

	.date-cell {
		font-weight: 500;
		color: var(--primary);
		white-space: nowrap;
	}

	.title-cell {
		min-width: 150px;
	}

	.grade-title {
		font-weight: 500;
		margin-bottom: 0.25rem;
	}

	.grade-description {
		font-size: 0.8rem;
		color: #666;
	}

	.grade-type-badge {
		display: inline-block;
		padding: 0.25rem 0.75rem;
		background: #e3f2fd;
		color: #1976d2;
		border-radius: 12px;
		font-size: 0.8rem;
		font-weight: 500;
	}

	.grade-value {
		font-weight: 600;
		font-size: 1.1rem;
	}

	/* Grade Colors */
	.grade-excellent { color: #2e7d32; }
	.grade-good { color: #558b2f; }
	.grade-satisfactory { color: #f57c00; }
	.grade-sufficient { color: #ef6c00; }
	.grade-poor { color: #d32f2f; }
	.grade-fail { color: #b71c1c; font-weight: bold; }
	.grade-none { color: #999; }

	/* Weight Cell */
	.weight-cell {
		white-space: nowrap;
	}

	.weight-edit {
		display: flex;
		align-items: center;
		gap: 0.5rem;
	}

	.weight-input {
		width: 60px;
		padding: 0.25rem 0.5rem;
		border: 1px solid #ddd;
		border-radius: 4px;
		font-size: 0.9rem;
	}

	.weight-btn {
		background: transparent;
		border: 1px solid var(--primary);
		color: var(--primary);
		padding: 0.25rem 0.5rem;
		border-radius: 4px;
		cursor: pointer;
		font-weight: 600;
		transition: all 0.2s;
	}

	.weight-btn:hover {
		background: var(--primary);
		color: white;
	}

	.btn-save {
		background: #4caf50;
		color: white;
		border: none;
		padding: 0.25rem 0.5rem;
		border-radius: 4px;
		cursor: pointer;
		font-size: 1rem;
		transition: background 0.2s;
	}

	.btn-save:hover {
		background: #45a049;
	}

	.btn-cancel {
		background: #f44336;
		color: white;
		border: none;
		padding: 0.25rem 0.5rem;
		border-radius: 4px;
		cursor: pointer;
		font-size: 1rem;
		transition: background 0.2s;
	}

	.btn-cancel:hover {
		background: #da190b;
	}

	.points-cell {
		color: #666;
	}

	.btn-delete {
		background: transparent;
		border: 1px solid #f44336;
		color: #f44336;
		padding: 0.4rem 0.75rem;
		border-radius: 4px;
		cursor: pointer;
		font-size: 0.85rem;
		font-weight: 500;
		transition: all 0.2s;
	}

	.btn-delete:hover {
		background: #f44336;
		color: white;
	}

	.no-data {
		text-align: center;
		padding: 2rem;
		color: #999;
		font-style: italic;
	}

	/* Subjects Grid */
	.subjects-grid {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
		gap: 1.5rem;
	}

	.subject-card {
		background: white;
		border-radius: 12px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
		padding: 1.5rem;
		text-align: left;
		border: none;
		cursor: pointer;
		transition: transform 0.2s, box-shadow 0.2s;
	}

	.subject-card:hover {
		transform: translateY(-4px);
		box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
	}

	.subject-card-header {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		margin-bottom: 1rem;
		padding-bottom: 1rem;
		border-bottom: 2px solid #f0f0f0;
	}

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

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

	.subject-details {
		display: flex;
		flex-direction: column;
		gap: 0.5rem;
		margin-bottom: 1rem;
	}

	.detail-row {
		display: flex;
		justify-content: space-between;
		font-size: 0.9rem;
	}

	.detail-label {
		color: #666;
		font-weight: 500;
	}

	.detail-value {
		color: #333;
	}

	.multiple-entries-info {
		background: #f0f4ff;
		padding: 0.5rem;
		border-radius: 4px;
		margin-bottom: 0.5rem;
	}

	.multiple-entries-info .detail-label {
		color: var(--primary);
		font-weight: 600;
	}

	.schedule-entry {
		padding-left: 1rem;
		font-size: 0.85rem;
	}

	.schedule-entry .detail-label {
		color: var(--primary);
	}

	.subject-preview {
		margin-top: 1rem;
		padding-top: 1rem;
		border-top: 1px solid #f0f0f0;
	}

	.preview-label {
		font-size: 0.85rem;
		color: #666;
		margin-bottom: 0.75rem;
		font-weight: 600;
	}

	.preview-grades {
		display: flex;
		flex-direction: column;
		gap: 0.5rem;
	}

	.preview-grade {
		display: flex;
		justify-content: space-between;
		font-size: 0.85rem;
	}

	.preview-name {
		color: #666;
	}

	.preview-value {
		font-weight: 600;
	}

	.preview-more {
		font-size: 0.8rem;
		color: #999;
		font-style: italic;
	}

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

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

		.subject-header {
			flex-direction: column;
		}

		.subject-stats {
			width: 100%;
			justify-content: space-around;
		}

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

		.student-grade-summary {
			text-align: left;
		}

		.grades-table-container {
			overflow-x: auto;
		}

		.grades-table {
			min-width: 600px;
		}

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