<script lang="ts">
	import { onMount } from 'svelte';
	import { authStore } from '$lib/stores/auth.svelte.js';
	import { api, type User, type UpdateUserDto } from '$lib/api';
	import { goto } from '$app/navigation';
	import { 
		UserPlus, 
		Trash2, 
		Edit2, 
		Save, 
		X, 
		Check, 
		Shield, 
		Mail, 
		Search 
	} from 'lucide-svelte';

	let users = $state<User[]>([]);
	let isLoading = $state(true);
	let error = $state<string | null>(null);
	let editingUser = $state<User | null>(null);
	let showEditModal = $state(false);
	let showDeleteConfirm = $state(false);
	let userToDelete = $state<User | null>(null);

	// Edit Form
	let editEmail = $state('');
	let editUsername = $state('');
	let editPassword = $state('');
	let editRole = $state<'Student' | 'Lehrer'>('Student');

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

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

		await loadUsers();
	});

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

		const response = await api.getUsers();

		if (response.data) {
			users = response.data;
		} else {
			error = response.error || 'Fehler beim Laden der Benutzer';
		}

		isLoading = false;
	}

	function openEditModal(user: User) {
		editingUser = user;
		editEmail = user.email;
		editUsername = user.username;
		editPassword = '';
		editRole = user.role;
		showEditModal = true;
	}

	function closeEditModal() {
		showEditModal = false;
		editingUser = null;
		editEmail = '';
		editUsername = '';
		editPassword = '';
		editRole = 'Student';
	}

	async function handleUpdateUser(e: Event) {
		e.preventDefault();

		if (!editingUser) return;

		const updateData: any = {
			email: editEmail,
			username: editUsername,
			role: editRole
		};

		if (editPassword) {
			updateData.password = editPassword;
		}

		const response = await api.updateUser(editingUser.id, updateData);

		if (response.data) {
			await loadUsers();
			closeEditModal();
		} else {
			error = response.error || 'Fehler beim Aktualisieren des Benutzers';
		}
	}

	function openDeleteConfirm(user: User) {
		userToDelete = user;
		showDeleteConfirm = true;
	}

	function closeDeleteConfirm() {
		showDeleteConfirm = false;
		userToDelete = null;
	}

	async function handleDeleteUser() {
		if (!userToDelete) return;

		const response = await api.deleteUser(userToDelete.id);

		if (response.data) {
			await loadUsers();
			closeDeleteConfirm();
		} else {
			error = response.error || 'Fehler beim Löschen des Benutzers';
			closeDeleteConfirm();
		}
	}

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

</script>

<div class="users-page">
	<div class="content">
		<div class="header-section">
			<h2>Nutzerverwaltung</h2>
			<p class="subtitle">Verwalten Sie alle Benutzer des Systems</p>
		</div>

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

		<div class="users-container">
			{#if isLoading}
				<div class="loading-state">
					<p>Lade Benutzer...</p>
				</div>
			{:else if users.length === 0}
				<div class="empty-state">
					<p>Keine Benutzer gefunden</p>
				</div>
			{:else}
				<div class="users-table">
					<table>
						<thead>
							<tr>
								<th>ID</th>
								<th>Benutzername</th>
								<th>E-Mail</th>
								<th>Rolle</th>
								<th>Erstellt am</th>
								<th>Aktionen</th>
							</tr>
						</thead>
						<tbody>
							{#each users as user}
								<tr>
									<td>{user.id}</td>
									<td>
										<div class="username">{user.username}</div>
									</td>
									<td>{user.email}</td>
									<td>
										<span class="role-badge {user.role === 'Lehrer' ? 'teacher' : 'student'}">
											{user.role}
										</span>
									</td>
									<td>{formatDate(user.createdAt)}</td>
									<td>
										<div class="actions">
											<button
												onclick={() => openEditModal(user)}
												class="btn-edit"
												title="Bearbeiten"
											>
												✏️
											</button>
											<button
												onclick={() => openDeleteConfirm(user)}
												class="btn-delete"
												title="Löschen"
												disabled={user.id === authStore.user?.id}
											>
												🗑️
											</button>
										</div>
									</td>
								</tr>
							{/each}
						</tbody>
					</table>
				</div>
			{/if}
		</div>
	</div>
</div>

<!-- Edit Modal -->
{#if showEditModal && editingUser}
	<div
		class="modal-backdrop"
		onclick={closeEditModal}
		onkeydown={(e) => e.key === 'Escape' && closeEditModal()}
		role="button"
		tabindex="0"
		aria-label="Schließe das Bearbeiten-Modal"
	>
		<div
			class="modal"
			onclick={(e) => e.stopPropagation()}
			onkeydown={(e) => e.stopPropagation()}
			role="dialog"
			aria-modal="true"
			aria-labelledby="edit-modal-title"
			tabindex="-1"
		>
			<div class="modal-header">
				<h3 id="edit-modal-title">Benutzer bearbeiten</h3>
				<button onclick={closeEditModal} class="modal-close">×</button>
			</div>
			<form onsubmit={handleUpdateUser}>
				<div class="modal-body">
					<div class="form-group">
						<label for="edit-email">E-Mail</label>
						<input type="email" id="edit-email" bind:value={editEmail} required />
					</div>

					<div class="form-group">
						<label for="edit-username">Benutzername</label>
						<input type="text" id="edit-username" bind:value={editUsername} required />
					</div>

					<div class="form-group">
						<label for="edit-password">Neues Passwort (optional)</label>
						<input
							type="password"
							id="edit-password"
							bind:value={editPassword}
							placeholder="Leer lassen, um nicht zu ändern"
						/>
					</div>

					<div class="form-group">
						<label for="edit-role">Rolle</label>
						<select id="edit-role" bind:value={editRole} required>
							<option value="Student">Student</option>
							<option value="Lehrer">Lehrer</option>
						</select>
					</div>
				</div>

				<div class="modal-footer">
					<button type="button" onclick={closeEditModal} class="btn-secondary">
						Abbrechen
					</button>
					<button type="submit" class="btn-primary">Speichern</button>
				</div>
			</form>
		</div>
	</div>
{/if}

<!-- Delete Confirmation Modal -->
{#if showDeleteConfirm && userToDelete}
	<div
		class="modal-backdrop"
		onclick={closeDeleteConfirm}
		onkeydown={(e) => e.key === 'Escape' && closeDeleteConfirm()}
		role="button"
		tabindex="0"
		aria-label="Schließe das Löschbestätigung-Modal"
	>
		<div
			class="modal modal-small"
			onclick={(e) => e.stopPropagation()}
			onkeydown={(e) => e.stopPropagation()}
			role="dialog"
			aria-modal="true"
			aria-labelledby="delete-modal-title"
			tabindex="-1"
		>
			<div class="modal-header">
				<h3 id="delete-modal-title">Benutzer löschen</h3>
				<button onclick={closeDeleteConfirm} class="modal-close">×</button>
			</div>
			<div class="modal-body">
				<p>
					Möchten Sie den Benutzer <strong>{userToDelete.username}</strong> wirklich löschen?
				</p>
				<p class="warning">Diese Aktion kann nicht rückgängig gemacht werden.</p>
			</div>
			<div class="modal-footer">
				<button onclick={closeDeleteConfirm} class="btn-secondary">Abbrechen</button>
				<button onclick={handleDeleteUser} class="btn-danger">Löschen</button>
			</div>
		</div>
	</div>
{/if}

<style>
	.users-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;
	}

	.users-container {
		background: white;
		border-radius: 12px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
		overflow: hidden;
	}

	.loading-state,
	.empty-state {
		padding: 3rem;
		text-align: center;
		color: #999;
	}

	.users-table {
		overflow-x: auto;
	}

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

	thead {
		background: #f9f9f9;
	}

	th {
		padding: 1rem;
		text-align: left;
		font-weight: 600;
		color: #333;
		font-size: 0.9rem;
		text-transform: uppercase;
		letter-spacing: 0.5px;
	}

	td {
		padding: 1rem;
		border-top: 1px solid #f0f0f0;
	}

	tbody tr {
		transition: background 0.2s;
	}

	tbody tr:hover {
		background: #f9f9f9;
	}

	.username {
		font-weight: 600;
		color: #333;
	}

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

	.role-badge.teacher {
		background: #e3f2fd;
		color: #1976d2;
	}

	.role-badge.student {
		background: #f3e5f5;
		color: #7b1fa2;
	}

	.actions {
		display: flex;
		gap: 0.5rem;
	}

	.btn-edit,
	.btn-delete {
		background: none;
		border: none;
		font-size: 1.25rem;
		cursor: pointer;
		padding: 0.25rem 0.5rem;
		border-radius: 4px;
		transition: background 0.2s;
	}

	.btn-edit:hover {
		background: #e8f5e9;
	}

	.btn-delete:hover:not(:disabled) {
		background: #ffebee;
	}

	.btn-delete:disabled {
		opacity: 0.3;
		cursor: not-allowed;
	}

	/* Modal Styles */
	.modal-backdrop {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 1000;
		padding: 1rem;
	}

	.modal {
		background: white;
		border-radius: 12px;
		width: 100%;
		max-width: 500px;
		max-height: 90vh;
		overflow: auto;
	}

	.modal-small {
		max-width: 400px;
	}

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

	.modal-header h3 {
		margin: 0;
		color: #333;
	}

	.modal-close {
		background: none;
		border: none;
		font-size: 2rem;
		cursor: pointer;
		color: #999;
		line-height: 1;
		padding: 0;
	}

	.modal-body {
		padding: 1.5rem;
	}

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

	.form-group:last-child {
		margin-bottom: 0;
	}

	label {
		display: block;
		margin-bottom: 0.5rem;
		font-weight: 600;
		color: #333;
		font-size: 0.9rem;
	}

	input,
	select {
		width: 100%;
		padding: 0.75rem;
		border: 2px solid #e1e1e1;
		border-radius: 6px;
		font-size: 1rem;
		transition: border-color 0.2s;
	}

	input:focus,
	select:focus {
		outline: none;
		border-color: var(--primary);
	}

	.warning {
		color: #ff5252;
		font-size: 0.9rem;
		margin-top: 1rem;
		margin-bottom: 0;
	}

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

	.btn-primary,
	.btn-secondary,
	.btn-danger {
		padding: 0.625rem 1.25rem;
		border: none;
		border-radius: 6px;
		font-weight: 600;
		cursor: pointer;
		transition: transform 0.2s, box-shadow 0.2s;
	}

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

	.btn-primary:hover {
		transform: translateY(-2px);
		box-shadow: 0 4px 12px rgba(60, 69, 240, 0.4);
	}

	.btn-secondary {
		background: #e1e1e1;
		color: #333;
	}

	.btn-secondary:hover {
		background: #d1d1d1;
	}

	.btn-danger {
		background: #ff5252;
		color: white;
	}

	.btn-danger:hover {
		background: #ff3838;
		transform: translateY(-2px);
		box-shadow: 0 4px 12px rgba(255, 82, 82, 0.4);
	}

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

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

		th,
		td {
			padding: 0.75rem 0.5rem;
			font-size: 0.85rem;
		}

		.modal {
			max-width: 100%;
		}
	}
</style>
