<script lang="ts">
	import { onMount } from 'svelte';
	import { page } from '$app/stores';
	import { apiService, type Part, type PdfFile } from '$lib/api';
	import PdfViewer from '$lib/components/PdfViewer.svelte';

	const INSTRUMENT_NAMES: Record<string, string> = {
		dir: 'Direction',
		pic: 'Piccolo',
		flu: 'Flûte',
		cla: 'Clarinette',
		clb: 'Clarinette basse',
		sax: 'Saxophone',
		sab: 'Saxophone baryton',
		sat: 'Saxophone ténor',
		cba: 'Contrebasse',
		cor: 'Cor',
		trp: 'Trompette',
		trb: 'Trombone',
		tub: 'Tuba',
		htb: 'Hautbois',
		bas: 'Basson',
		per: 'Percussion',
		crn: 'Cornet',
		eup: 'Euphonium',
		har: 'Harpe',
		pia: 'Piano'
	};

	function getInstrumentName(code: string): string {
		return INSTRUMENT_NAMES[code] || code;
	}

	let scoreId = '';
	let pieceId = '';
	let instrumentCode = '';
	let instrumentTitle = '';
	let parts: Part[] = $state([]);
	let loading = $state(true);
	let error = $state('');
	let selectedFile = $state('');
	let showSidebar = $state(true);
	let pieceName = $state('');
	let pieceCount = $state(0);

	let pdfViewerUrl = $derived(selectedFile ? apiService.getDownloadUrl(selectedFile) : '');
	let pdfFileName = $derived(selectedFile ? selectedFile.split('/').pop() || 'Partition' : 'Partition');

	page.subscribe(($page) => {
		scoreId = $page.params.id || '';
		pieceId = $page.params.piece || '';
		instrumentCode = $page.params.instrument || '';
	});

	onMount(async () => {
		try {
			// Get pieces info
			const pieces = await apiService.getPieces(scoreId);
			pieceCount = pieces.length;
			const piece = pieces.find(p => p.id.toString() === pieceId);
			if (piece) {
				pieceName = piece.name;
			}
			
			const score = await apiService.getScore(scoreId);
			const instrument = (score.instruments || []).find(
				i => i.id === instrumentCode && i.piece === pieceId
			);
			if (instrument) {
				instrumentTitle = instrument.title;
				parts = instrument.parts || [];
			}
			if (parts.length > 0 && parts[0].files.length > 0) {
				selectedFile = parts[0].files[0].path;
			}
		} catch (err) {
			error = 'Erreur lors du chargement des parties';
			console.error(err);
		} finally {
			loading = false;
		}
	});

	function getFileInfo(file: PdfFile): string {
		const info = [];
		if (file.part) info.push(`Partie ${file.part}`);
		if (file.key) info.push(file.key);
		if (file.clef) info.push(file.clef);
		if (file.variant) info.push(file.variant);
		return info.length > 0 ? `(${info.join(', ')})` : '';
	}

	async function downloadFile(path: string) {
		try {
			const blob = await apiService.downloadPdf(path);
			const url = window.URL.createObjectURL(blob);
			const a = document.createElement('a');
			a.href = url;
			a.download = path.split('/').pop() || 'partition.pdf';
			document.body.appendChild(a);
			a.click();
			window.URL.revokeObjectURL(url);
			a.remove();
		} catch (err) {
			console.error('Error downloading:', err);
		}
	}

	function openViewer(path: string) {
		selectedFile = path;
	}
</script>

<svelte:head>
	<title>{instrumentTitle || instrumentCode} - {scoreId} - OHMJ</title>
</svelte:head>

<div class="h-[calc(100vh-64px)] flex flex-col">
	<div class="container mx-auto px-4 py-4">
		<a href="/scores/{scoreId}?piece={pieceId}" class="inline-flex items-center text-ohmj-primary hover:underline mb-4">
			← Retour aux instruments
		</a>

		<h1 class="text-2xl font-bold text-ohmj-primary">
			Partition {scoreId} - {instrumentTitle || getInstrumentName(instrumentCode)}{pieceCount > 1 ? (pieceName ? ' - ' + pieceName : ' - Pièce ' + pieceId) : ''}
		</h1>
	</div>

	{#if loading}
		<div class="flex justify-center items-center py-20">
			<div class="animate-spin rounded-full h-12 w-12 border-b-2 border-ohmj-primary"></div>
		</div>
	{:else if error}
		<div class="container mx-auto px-4">
			<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
				{error}
			</div>
		</div>
	{:else}
		<div class="flex-1 flex overflow-hidden relative">
			<!-- Toggle button -->
			<button
				onclick={() => showSidebar = !showSidebar}
				class="absolute left-0 top-1/2 transform -translate-y-1/2 z-10 bg-ohmj-primary text-white px-2 py-4 rounded-r shadow hover:bg-ohmj-secondary transition-colors"
				title={showSidebar ? 'Masquer' : 'Afficher'}
			>
				{showSidebar ? '◀' : '▶'}
			</button>
			
			<!-- Liste des parties -->
			{#if showSidebar}
			<div class="w-64 min-w-[200px] max-w-xs bg-white border-r overflow-y-auto p-4 flex-shrink-0 ml-8">
				<h2 class="font-semibold text-gray-700 mb-4">Parties disponibles</h2>
				
				{#each parts as part}
					<div class="mb-4">
						{#if parts.length > 1}
							<h3 class="font-medium text-gray-800 mb-2">Version {part.id}</h3>
						{/if}
						<ul class="space-y-1">
							{#each part.files as file}
								<li class="flex items-stretch gap-1 rounded overflow-hidden border border-gray-200 hover:border-ohmj-primary transition-colors">
									<button
										onclick={() => openViewer(file.path)}
										class="flex-1 text-left px-3 py-2 bg-white hover:bg-ohmj-light text-sm text-ohmj-primary font-medium"
									>
										📖 {file.name} {getFileInfo(file)}
									</button>
									<button
										onclick={() => downloadFile(file.path)}
										class="px-3 py-2 bg-gray-50 hover:bg-gray-100 text-gray-600 hover:text-ohmj-primary transition-colors text-sm"
										title="Télécharger"
									>
										<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
											<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
										</svg>
									</button>
								</li>
							{/each}
						</ul>
					</div>
				{/each}

				{#if parts.length === 0}
					<p class="text-gray-500">Aucune partie disponible.</p>
				{/if}
			</div>
			{/if}

			<!-- Visionneuse PDF -->
			<div class="flex-1 bg-gray-800 flex flex-col ml-8">
				{#if selectedFile}
					{#key selectedFile}
						<PdfViewer pdfUrl={pdfViewerUrl} title={pdfFileName} />
					{/key}
				{:else}
					<div class="h-full flex items-center justify-center text-gray-400">
						<p>Sélectionnez une partition pour la visionner</p>
					</div>
				{/if}
			</div>
		</div>
	{/if}
</div>
