<script lang="ts">
	import { onMount, onDestroy } from 'svelte';
	import { api, type AttendanceStatus } from '$lib/api';
	import { Users, UserCheck, UserX, Clock, RefreshCw } from 'lucide-svelte';

	let status = $state<AttendanceStatus | null>(null);
	let isLoading = $state(true);
	let error = $state<string | null>(null);
	let lastUpdate = $state<Date>(new Date());
    let intervalId: any;

	async function loadAttendance() {
		const response = await api.getPresentStudents();
		if (response.data) {
			status = response.data;
			lastUpdate = new Date();
			error = null;
		} else {
			error = response.error || 'Fehler beim Laden der Anwesenheit';
		}
		isLoading = false;
	}

	onMount(() => {
		loadAttendance();
		// Poll every 5 seconds
		intervalId = setInterval(loadAttendance, 5000);
	});

	onDestroy(() => {
		if (intervalId) clearInterval(intervalId);
	});

    function formatTime(isoString: string) {
        return new Date(isoString).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    }
</script>

<div class="card attendance-card">
	<div class="card-header">
		<div class="header-title">
			<h3>Anwesenheit</h3>
		</div>
		<span class="icon"><Users size={24} /></span>
	</div>

	<div class="card-body">
		{#if isLoading && !status}
			<div class="loading-container">
				<span class="loading-spinner"></span>
				<p>Lade Anwesenheit...</p>
			</div>
		{:else if error}
			<div class="alert alert-error">
				<p>{error}</p>
				<button class="btn btn-sm btn-secondary" onclick={loadAttendance}>
					<RefreshCw size={16} /> Neu laden
				</button>
			</div>
		{:else if status}
			<div class="stats-row">
				<div class="stat-item present">
					<span class="stat-label">Anwesend</span>
					<span class="stat-value">{status.totalPresent}</span>
				</div>
			</div>

			<div class="list-container">
				{#if status.presentStudents.length === 0}
					<p class="empty-state">Keine Schüler anwesend</p>
				{:else}
					<ul class="student-list">
						{#each status.presentStudents as student}
							<li class="student-item">
								<div class="student-info">
									<span class="student-name">{student.name}</span>
									<span class="student-class">{student.className || '-'}</span>
								</div>
								<div class="checkin-info">
									<Clock size={14} />
									<span>{formatTime(student.checkInTime)}</span>
									<span class="duration">({student.minutesPresent} min)</span>
								</div>
							</li>
						{/each}
					</ul>
				{/if}
			</div>

            <div class="footer-info">
                Stand: {lastUpdate.toLocaleTimeString()}
            </div>
		{/if}
	</div>
</div>

<style>
	.attendance-card {
		height: 100%;
		display: flex;
		flex-direction: column;
	}

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

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

    .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-body {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.stats-row {
		display: grid;
		grid-template-columns: 1fr;
		gap: var(--space-md);
		margin-bottom: var(--space-md);
	}

	.stat-item {
		background: var(--neutral-50);
		padding: var(--space-sm);
		border-radius: var(--radius-sm);
		text-align: center;
	}

	.stat-item.present {
		border: 1px solid var(--neutral-200);
	}

	.stat-label {
		display: block;
		font-size: var(--text-xs);
		color: var(--neutral-600);
		text-transform: uppercase;
	}

	.stat-value {
		display: block;
		font-size: var(--text-xl);
		font-weight: bold;
		color: var(--neutral-900);
	}

	.list-container {
		flex: 1;
		overflow-y: auto;
		max-height: 300px;
        min-height: 100px;
	}

	.student-list {
		list-style: none;
		padding: 0;
		margin: 0;
	}

	.student-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: var(--space-xs) 0;
		border-bottom: 1px solid var(--neutral-100);
	}

	.student-item:last-child {
		border-bottom: none;
	}

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

	.student-class {
		font-size: var(--text-xs);
		color: var(--neutral-500);
	}

	.checkin-info {
		display: flex;
		align-items: center;
		gap: 4px;
		font-size: var(--text-xs);
		color: var(--success-600);
	}

    .duration {
        color: var(--neutral-400);
    }

	.empty-state {
		text-align: center;
		color: var(--neutral-500);
		padding: var(--space-lg) 0;
	}

	.loading-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: var(--space-xl);
		gap: var(--space-md);
		color: var(--neutral-500);
	}

    .footer-info {
        margin-top: var(--space-sm);
        text-align: right;
        font-size: 0.7rem;
        color: var(--neutral-400);
    }
</style>
