<script lang="ts">
	import { onMount } from 'svelte';
	import { page } from '$app/stores';
	import { apiService, type Score, type Piece } from '$lib/api';
	import { goto } from '$app/navigation';

	const INSTRUMENT_ICONS: Record<string, string> = {
		dir: '🎼', pic: '/icons/piccolo.png', flu: '/icons/flute.png', cla: '/icons/clarinette.png', clb: '/icons/clarinette_basse.png',
		sax: '/icons/sax-alto.png', sab: '/icons/sax-barython.png', sat: '/icons/sax-tenor.png', coa: '/icons/cor-anglais.jpg', cba: '/icons/contrebasse.png',
		cor: '/icons/cor.png', trp: '/icons/trumpet.png', trb: '/icons/tronbonne.png', tub: '/icons/tuba.png', htb: '/icons/hautbois.png',
		bas: '/icons/basson.png', per: '/icons/percussion.png', crn: '/icons/cornet.png', eup: '/icons/euphonium.png', har: '/icons/harpe.png',
		pia: '🎹', sup: '📄', par: '📄'
	};

	const INSTRUMENT_NAMES: Record<string, string> = {
		dir: 'Direction', pic: 'Piccolo', flu: 'Flûte', cla: 'Clarinette',
		clb: 'Clarinette Basse', sax: 'Sax Alto', sat: 'Sax Ténor', sab: 'Sax Baryton',
		coa: 'Cor Anglais', cba: 'Contrebasse', cor: 'Cor', trp: 'Trompette',
		trb: 'Trombone', tub: 'Tuba', htb: 'Hautbois', bas: 'Basson',
		per: 'Percussions', crn: 'Cornet', eup: 'Euphonium', har: 'Harpe',
		pia: 'Piano', sup: 'Parties supplementaires', par: 'Parties'
	};

	function getInstrumentIcon(code: string): string {
		return INSTRUMENT_ICONS[code] || '🎵';
	}

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

	let scoreId = '';
	let score: Score | null = null;
	let pieces: Piece[] = [];
	let instruments: any[] = [];
	let loading = $state(true);
	let error = $state('');
	let selectedPiece = $state(1);

	page.subscribe(($page) => {
		scoreId = $page.params.id || '';
		// Read piece from URL param or query string
		const pieceParam = $page.params.piece || $page.url.searchParams.get('piece');
		if (pieceParam) {
			selectedPiece = parseInt(pieceParam) || 1;
		}
	});

	onMount(async () => {
		try {
			score = await apiService.getScore(scoreId);
			pieces = await apiService.getPieces(scoreId);
			
			// Set default piece to 1 if not in URL
			if (pieces.length > 0 && !pieces.find(p => p.id === selectedPiece)) {
				selectedPiece = pieces[0].id;
			}
			
			// Load instruments for the selected piece
			await loadInstrumentsForPiece(selectedPiece);
		} catch (err) {
			error = 'Erreur lors du chargement';
			console.error(err);
		} finally {
			loading = false;
		}
	});

	async function loadInstrumentsForPiece(pieceId: number) {
		loading = true;
		try {
			instruments = await apiService.getInstruments(scoreId, pieceId);
		} catch (err) {
			console.error('Error loading instruments:', err);
			error = 'Erreur lors du chargement des instruments';
		} finally {
			loading = false;
		}
	}

	async function selectPiece(pieceId: number) {
		selectedPiece = pieceId;
		await loadInstrumentsForPiece(pieceId);
	}
</script>

<svelte:head>
	<title>{score?.name || 'Partition'} - OHMJ</title>
</svelte:head>

<div class="container mx-auto px-4 py-8">
	<a href="/scores" class="inline-flex items-center text-ohmj-primary hover:underline mb-4">
		← Retour aux partitions
	</a>

	{#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="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
			{error}
		</div>
	{:else}
		<div class="mb-6">
			<h1 class="text-3xl font-bold text-ohmj-primary">{score?.name || ''}</h1>
			{#if score?.compositor}
				<p class="text-gray-600 mt-1 text-lg">{score.compositor}</p>
			{/if}
			{#if score?.ressource}
				<a
					href={score.ressource}
					target="_blank"
					rel="noopener noreferrer"
					class="inline-flex items-center mt-2 text-ohmj-primary hover:underline"
				>
					🔗 Ressource externe
				</a>
			{/if}
			<p class="text-sm text-gray-400 mt-1">№ {scoreId}</p>
		</div>

		{#if pieces.length > 1}
			<h2 class="text-xl font-semibold text-gray-700 mb-4">Pièces</h2>
			<div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4 mb-8">
				{#each pieces as piece}
					<button
						onclick={() => selectPiece(piece.id)}
						class="bg-white p-4 rounded-lg shadow hover:shadow-lg transition-shadow border-2 {selectedPiece === piece.id ? 'border-ohmj-primary' : 'border-transparent hover:border-ohmj-primary'}"
					>
						<p class="font-semibold text-gray-800">{piece.name}</p>
						<p class="text-sm text-gray-500">№ {piece.id}</p>
					</button>
				{/each}
			</div>
		{/if}

		{#if pieces.length <= 1 || selectedPiece}
			<h2 class="text-xl font-semibold text-gray-700 mb-4">Instruments disponibles</h2>
			
			{#if instruments.length === 0}
				<p class="text-gray-500">Aucun instrument trouvé.</p>
			{:else}
				<div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
					{#each instruments as instrument}
						{@const code = instrument.id || instrument.code || ''}
						{@const title = instrument.title || getInstrumentName(code)}
						{@const fileCount = instrument.parts?.[0]?.files?.length || 0}
						{@const icon = getInstrumentIcon(code)}
						<a
							href="/scores/{scoreId}/{selectedPiece}/{code}"
							class="bg-white p-6 rounded-lg shadow hover:shadow-lg transition-shadow border border-gray-200 hover:border-ohmj-primary"
						>
							<div class="text-center">
								<div class="text-4xl mb-2">
									{#if icon.startsWith('/')}
										<img src={icon} alt={title} class="w-12 h-12 mx-auto object-contain" />
									{:else}
										{icon}
									{/if}
								</div>
								<h3 class="font-semibold text-gray-800">{title}</h3>
								<p class="text-sm text-gray-500 mt-1">{fileCount} partie{fileCount !== 1 ? 's' : ''}</p>
							</div>
						</a>
					{/each}
				</div>
			{/if}
		{/if}
	{/if}
</div>
