<script lang="ts">
	import type { StudentHomework, StudentHomeworkDetail as HomeworkDetailType } from '$lib/features/homework/api/studentHomework';
	import { fetchStudentHomework, fetchHomeworkDetail } from '$lib/features/homework/api/studentHomework';
	import { toggleHomeworkDone, getHomeworkStatuses } from '$lib/features/homework/stores/homeworkStatus.svelte';
	import { isOffline } from '$lib/features/schedule/stores/scheduleCache.svelte';
	import HomeworkCard from './HomeworkCard.svelte';
	import HomeworkDetail from './HomeworkDetail.svelte';
	import HomeworkSubmissionForm from '$lib/components/organisms/HomeworkSubmission/HomeworkSubmissionForm.svelte';
	import SkeletonList from '$lib/components/atoms/Skeleton/SkeletonList.svelte';

	let homeworks = $state<StudentHomework[]>([]);
	let allSubjects = $state<{ id: string; name: string; color: string | null }[]>([]);
	let loading = $state(true);
	let error = $state<string | null>(null);
	let selectedSubjectId = $state<string | null>(null);
	let selectedDetail = $state<HomeworkDetailType | null>(null);
	let showSubmissionForm = $state(false);
	let detailLoading = $state(false);

	let statuses = $derived(getHomeworkStatuses());

	let pendingHomeworks = $derived(
		homeworks.filter(hw => !statuses[hw.id]?.done)
	);

	let doneHomeworks = $derived(
		homeworks.filter(hw => statuses[hw.id]?.done)
	);

	function extractSubjects(hws: StudentHomework[]): { id: string; name: string; color: string | null }[] {
		const map = new Map<string, { id: string; name: string; color: string | null }>();
		for (const hw of hws) {
			if (!map.has(hw.subjectId)) {
				map.set(hw.subjectId, { id: hw.subjectId, name: hw.subjectName, color: hw.subjectColor });
			}
		}
		return Array.from(map.values());
	}

	async function loadHomeworks() {
		loading = true;
		error = null;

		try {
			homeworks = await fetchStudentHomework(selectedSubjectId ?? undefined);
			if (selectedSubjectId === null) {
				allSubjects = extractSubjects(homeworks);
			}
		} catch (e) {
			error = e instanceof Error ? e.message : 'Erreur de chargement';
		} finally {
			loading = false;
		}
	}

	function handleFilterChange(subjectId: string | null) {
		selectedSubjectId = subjectId;
	}

	async function handleCardClick(homeworkId: string) {
		detailLoading = true;

		try {
			selectedDetail = await fetchHomeworkDetail(homeworkId);
		} catch {
			// Stay on list if detail fails
		} finally {
			detailLoading = false;
		}
	}

	function handleBack() {
		selectedDetail = null;
		showSubmissionForm = false;
	}

	function handleOpenSubmissionForm() {
		showSubmissionForm = true;
	}

	function handleSubmissionBack() {
		showSubmissionForm = false;
	}

	function handleSubmitted() {
		// Laisser le message de succès visible brièvement avant de revenir à la liste
		window.setTimeout(() => {
			showSubmissionForm = false;
			selectedDetail = null;
			void loadHomeworks();
		}, 1500);
	}

	function handleToggleDone(homeworkId: string) {
		toggleHomeworkDone(homeworkId);
	}

	$effect(() => {
		void selectedSubjectId;
		void loadHomeworks();
	});
</script>

{#if selectedDetail && showSubmissionForm}
	<HomeworkSubmissionForm detail={selectedDetail} onBack={handleSubmissionBack} onSubmitted={handleSubmitted} />
{:else if selectedDetail}
	<HomeworkDetail detail={selectedDetail} onBack={handleBack} onSubmit={handleOpenSubmissionForm} />
{:else}
	<div class="student-homework">
		{#if isOffline()}
			<div class="offline-banner" role="status">
				<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
					<line x1="1" y1="1" x2="23" y2="23"/>
					<path d="M16.72 11.06A10.94 10.94 0 0 1 19 12.55"/>
					<path d="M5 12.55a10.94 10.94 0 0 1 5.17-2.39"/>
					<path d="M10.71 5.05A16 16 0 0 1 22.56 9"/>
					<path d="M1.42 9a15.91 15.91 0 0 1 4.7-2.88"/>
					<path d="M8.53 16.11a6 6 0 0 1 6.95 0"/>
					<line x1="12" y1="20" x2="12.01" y2="20"/>
				</svg>
				Mode hors ligne
			</div>
		{/if}

		{#if allSubjects.length > 1}
			<div class="filter-bar" role="toolbar" aria-label="Filtrer par matière">
				<button
					class="filter-chip"
					class:active={selectedSubjectId === null}
					onclick={() => handleFilterChange(null)}
				>
					Tous
				</button>
				{#each allSubjects as subject}
					<button
						class="filter-chip"
						class:active={selectedSubjectId === subject.id}
						style:--chip-color={subject.color ?? '#3b82f6'}
						onclick={() => handleFilterChange(subject.id)}
					>
						{subject.name}
					</button>
				{/each}
			</div>
		{/if}

		{#if loading}
			<SkeletonList items={4} message="Chargement des devoirs..." />
		{:else if error}
				<div class="error-message" role="alert">
					<p>{error}</p>
					<button onclick={() => void loadHomeworks()}>Réessayer</button>
				</div>
		{:else if homeworks.length === 0}
			<div class="empty-state">
				<p>Aucun devoir pour le moment</p>
			</div>
		{:else}
			{#if pendingHomeworks.length > 0}
				<section>
					<h3 class="section-title">À faire ({pendingHomeworks.length})</h3>
					<ul class="homework-list" role="list">
						{#each pendingHomeworks as hw (hw.id)}
							<li>
								<HomeworkCard
									homework={hw}
									isDone={false}
									onToggleDone={handleToggleDone}
									onclick={handleCardClick}
								/>
							</li>
						{/each}
					</ul>
				</section>
			{/if}

			{#if doneHomeworks.length > 0}
				<section>
					<h3 class="section-title">Terminés ({doneHomeworks.length})</h3>
					<ul class="homework-list" role="list">
						{#each doneHomeworks as hw (hw.id)}
							<li>
								<HomeworkCard
									homework={hw}
									isDone={true}
									onToggleDone={handleToggleDone}
									onclick={handleCardClick}
								/>
							</li>
						{/each}
					</ul>
				</section>
			{/if}
		{/if}

		{#if detailLoading}
			<div class="detail-loading-overlay" role="status">
				<p>Chargement...</p>
			</div>
		{/if}
	</div>
{/if}

<style>
	.student-homework {
		display: flex;
		flex-direction: column;
		gap: 1rem;
	}

	.offline-banner {
		display: flex;
		align-items: center;
		gap: 0.5rem;
		padding: 0.5rem 0.75rem;
		background: #fef3c7;
		border: 1px solid #f59e0b;
		border-radius: 0.5rem;
		color: #92400e;
		font-size: 0.8125rem;
		font-weight: 500;
	}

	.filter-bar {
		display: flex;
		gap: 0.5rem;
		flex-wrap: wrap;
	}

	.filter-chip {
		padding: 0.375rem 0.75rem;
		border: 1px solid #e5e7eb;
		border-radius: 1rem;
		background: white;
		font-size: 0.8125rem;
		cursor: pointer;
		transition: background 0.15s, border-color 0.15s;
	}

	.filter-chip:hover {
		background: #f3f4f6;
	}

	.filter-chip.active {
		background: var(--chip-color, #3b82f6);
		color: white;
		border-color: var(--chip-color, #3b82f6);
	}

	.section-title {
		margin: 0 0 0.5rem;
		font-size: 0.875rem;
		font-weight: 600;
		color: #6b7280;
		text-transform: uppercase;
		letter-spacing: 0.025em;
	}

	.homework-list {
		list-style: none;
		margin: 0;
		padding: 0;
		display: flex;
		flex-direction: column;
		gap: 0.5rem;
	}

	.empty-state {
		text-align: center;
		padding: 2rem;
		color: #6b7280;
	}

	.error-message {
		text-align: center;
		padding: 1rem;
		color: #ef4444;
	}

	.error-message button {
		margin-top: 0.5rem;
		padding: 0.375rem 0.75rem;
		border: 1px solid #ef4444;
		border-radius: 0.375rem;
		background: white;
		color: #ef4444;
		cursor: pointer;
	}

	.detail-loading-overlay {
		position: fixed;
		inset: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		background: rgba(255, 255, 255, 0.8);
		z-index: 50;
	}
</style>
