<script lang="ts">
	import type { StudentHomeworkDetail } from '$lib/features/homework/api/studentHomework';
	import { getAttachmentUrl as defaultGetAttachmentUrl } from '$lib/features/homework/api/studentHomework';
	import { authenticatedFetch } from '$lib/auth';

	let {
		detail,
		onBack,
		onSubmit,
		getAttachmentUrl = defaultGetAttachmentUrl
	}: {
		detail: StudentHomeworkDetail;
		onBack: () => void;
		onSubmit?: () => void;
		getAttachmentUrl?: (homeworkId: string, attachmentId: string) => string;
	} = $props();

	function formatDueDate(dateStr: string): string {
		const date = new Date(dateStr + 'T00:00:00');
		return date.toLocaleDateString('fr-FR', {
			weekday: 'long',
			day: 'numeric',
			month: 'long',
			year: 'numeric'
		});
	}

	function formatFileSize(bytes: number): string {
		if (bytes < 1024) return `${bytes} o`;
		if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} Ko`;
		return `${(bytes / (1024 * 1024)).toFixed(1)} Mo`;
	}

	function shouldOpenInline(mimeType: string): boolean {
		return mimeType === 'application/pdf' || mimeType.startsWith('image/') || mimeType.startsWith('text/');
	}

	function triggerBlobNavigation(blobUrl: string, filename: string, inline: boolean): void {
		const link = document.createElement('a');
		link.href = blobUrl;

		if (inline) {
			link.target = '_blank';
			link.rel = 'noopener noreferrer';
		} else {
			link.download = filename;
		}

		link.click();
		window.setTimeout(() => URL.revokeObjectURL(blobUrl), 60_000);
	}

	let downloadError = $state<string | null>(null);

	async function downloadAttachment(attachmentId: string, filename: string, mimeType: string) {
		downloadError = null;
		const url = getAttachmentUrl(detail.id, attachmentId);

		try {
			const response = await authenticatedFetch(url);

			if (!response.ok) {
				downloadError = `Impossible de télécharger "${filename}".`;
				return;
			}

				const blob = await response.blob();
				const blobUrl = URL.createObjectURL(blob);
				triggerBlobNavigation(blobUrl, filename, shouldOpenInline(mimeType));
			} catch {
				downloadError = `Impossible de télécharger "${filename}".`;
			}
		}
</script>

<div class="homework-detail">
	<button class="back-button" onclick={onBack}>
		<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
			<path d="M19 12H5M12 19l-7-7 7-7"/>
		</svg>
		Retour
	</button>

	<header class="detail-header" style:border-left-color={detail.subjectColor ?? '#3b82f6'}>
		<span class="subject-name" style:color={detail.subjectColor ?? '#3b82f6'}>
			{detail.subjectName}
		</span>
		<h2 class="detail-title">{detail.title}</h2>
		<div class="detail-meta">
			<span class="due-date">Pour le {formatDueDate(detail.dueDate)}</span>
			<span class="teacher-name">Par {detail.teacherName}</span>
		</div>
	</header>

	{#if detail.description}
		<section class="detail-description">
			<h3>Description</h3>
			<div class="description-content">{@html detail.description}</div>
		</section>
	{/if}

	{#if onSubmit}
		<div class="submit-section">
			<button class="btn-submit-homework" onclick={onSubmit}>
				Rendre mon devoir
			</button>
		</div>
	{/if}

	{#if detail.attachments.length > 0}
		<section class="detail-attachments">
			<h3>Pièces jointes</h3>
			{#if downloadError}
				<p class="download-error" role="alert">{downloadError}</p>
			{/if}
			<ul class="attachments-list">
				{#each detail.attachments as attachment}
						<li>
							<button
								class="attachment-item"
								onclick={() =>
									downloadAttachment(attachment.id, attachment.filename, attachment.mimeType)}
							>
								<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
									<path d="M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"/>
								</svg>
							<span class="attachment-name">{attachment.filename}</span>
							<span class="attachment-size">{formatFileSize(attachment.fileSize)}</span>
						</button>
					</li>
				{/each}
			</ul>
		</section>
	{/if}
</div>

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

	.back-button {
		display: inline-flex;
		align-items: center;
		gap: 0.375rem;
		background: none;
		border: none;
		color: #3b82f6;
		font-size: 0.875rem;
		font-weight: 500;
		cursor: pointer;
		padding: 0.25rem 0;
		align-self: flex-start;
	}

	.back-button:hover {
		color: #2563eb;
	}

	.detail-header {
		border-left: 4px solid #3b82f6;
		padding-left: 1rem;
	}

	.subject-name {
		font-size: 0.75rem;
		font-weight: 600;
		text-transform: uppercase;
	}

	.detail-title {
		margin: 0.25rem 0 0.5rem;
		font-size: 1.25rem;
		font-weight: 600;
		color: #1f2937;
	}

	.detail-meta {
		display: flex;
		flex-direction: column;
		gap: 0.125rem;
		font-size: 0.875rem;
		color: #6b7280;
	}

	.detail-description h3,
	.detail-attachments h3 {
		margin: 0 0 0.5rem;
		font-size: 0.9375rem;
		font-weight: 600;
		color: #374151;
	}

	.detail-description :global(.description-content) {
		color: #4b5563;
		line-height: 1.6;
	}

	.detail-description :global(.description-content p) {
		margin: 0 0 0.5rem;
	}

	.detail-description :global(.description-content p:last-child) {
		margin-bottom: 0;
	}

	.detail-description :global(.description-content ul) {
		list-style-type: disc;
		padding-left: 1.5rem;
		margin: 0 0 0.5rem;
	}

	.detail-description :global(.description-content ol) {
		list-style-type: decimal;
		padding-left: 1.5rem;
		margin: 0 0 0.5rem;
	}

	.detail-description :global(.description-content a) {
		color: #2563eb;
		text-decoration: underline;
	}

	.download-error {
		margin: 0 0 0.5rem;
		padding: 0.5rem 0.75rem;
		background: #fee2e2;
		border-radius: 0.375rem;
		color: #991b1b;
		font-size: 0.8125rem;
	}

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

	.attachment-item {
		display: flex;
		align-items: center;
		gap: 0.5rem;
		width: 100%;
		padding: 0.625rem 0.75rem;
		background: #f9fafb;
		border: 1px solid #e5e7eb;
		border-radius: 0.375rem;
		cursor: pointer;
		text-align: left;
		font-size: 0.875rem;
	}

	.attachment-item:hover {
		background: #f3f4f6;
		border-color: #d1d5db;
	}

	.attachment-name {
		flex: 1;
		color: #3b82f6;
		font-weight: 500;
	}

	.attachment-size {
		color: #9ca3af;
		font-size: 0.75rem;
	}

	.submit-section {
		padding-top: 0.5rem;
	}

	.btn-submit-homework {
		display: inline-flex;
		align-items: center;
		gap: 0.375rem;
		padding: 0.625rem 1.25rem;
		border: none;
		border-radius: 0.375rem;
		background: #3b82f6;
		color: white;
		font-size: 0.9375rem;
		font-weight: 500;
		cursor: pointer;
		transition: background-color 0.15s;
	}

	.btn-submit-homework:hover {
		background: #2563eb;
	}
</style>
