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

	const INSTRUMENTS = [
		{ code: 'dir', name: 'Direction', defaultKey: '' },
		{ code: 'pic', name: 'Piccolo', defaultKey: 'do' },
		{ code: 'flu', name: 'Flûte', defaultKey: 'do' },
		{ code: 'cla', name: 'Clarinette', defaultKey: 'sib' },
		{ code: 'clb', name: 'Clarinette Basse', defaultKey: 'sib' },
		{ code: 'sax', name: 'Saxophone Alto', defaultKey: 'mib' },
		{ code: 'sat', name: 'Saxophone Ténor', defaultKey: 'sib' },
		{ code: 'sab', name: 'Saxophone Baryton', defaultKey: 'mib' },
		{ code: 'coa', name: 'Cor Anglais', defaultKey: 'fa' },
		{ code: 'htb', name: 'Hautbois', defaultKey: 'do' },
		{ code: 'bas', name: 'Basson', defaultKey: 'do' },
		{ code: 'cor', name: 'Cor', defaultKey: 'fa' },
		{ code: 'trp', name: 'Trompette', defaultKey: 'sib' },
		{ code: 'crn', name: 'Cornet', defaultKey: 'sib' },
		{ code: 'trb', name: 'Trombone', defaultKey: 'do' },
		{ code: 'eup', name: 'Euphonium', defaultKey: 'sib' },
		{ code: 'tub', name: 'Tuba', defaultKey: 'do' },
		{ code: 'cba', name: 'Contrebasse', defaultKey: 'sib' },
		{ code: 'per', name: 'Percussions', defaultKey: '' },
		{ code: 'pia', name: 'Piano', defaultKey: '' },
		{ code: 'har', name: 'Harpe', defaultKey: '' }
	];

	let scores: Score[] = $state([]);
	let loading = $state(true);
	let error = $state('');
	let userRole = $state('');
	let isAdmin = $derived(userRole === 'admin');

	// Form for new score
	let showForm = $state(false);
	let newName = $state('');
	let newCompositor = $state('');
	let newPieceCount = $state(1);
	let newPieceNames = $state<string[]>(['']);
	let saving = $state(false);

	 // Upload form
	let uploadScoreId = $state('');
	let uploadPiece = $state('1');
	let uploadInstrument = $state('');
	let uploadVersion = $state('1');
	let uploadFile: File | null = $state(null);
	let uploading = $state(false);
	let uploadError = $state('');
	let uploadSuccess = $state('');
	let selectedScorePieceCount = $state(1);
	let selectedScorePieces = $state<{id: string; name: string}[]>([]);
	let showAdvanced = $state(false);
	let deleteConfirmId = $state<string | null>(null);
	let uploadKey = $state('');
	let uploadClef = $state('');
	let uploadVariant = $state('');
	let uploadPart = $state('1');

	function handlePieceCountChange(count: number) {
		newPieceCount = count;
		newPieceNames = Array(count).fill('').map((_, i) => newPieceNames[i] || '');
	}

	// When score is selected, get piece count
	async function handleScoreSelect(e: Event) {
		const target = e.target as HTMLSelectElement;
		uploadScoreId = target.value;
		if (uploadScoreId) {
			try {
				const pieces = await apiService.getPieces(uploadScoreId);
				selectedScorePieceCount = pieces.length;
				selectedScorePieces = pieces.map((p: any) => ({
					id: String(p.id),
					name: p.name || `Partie ${p.id}`
				}));
				if (selectedScorePieceCount === 1) {
					uploadPiece = '1';
				}
			} catch (err) {
				console.error(err);
				selectedScorePieceCount = 1;
				selectedScorePieces = [];
			}
		}
	}

	function getExpectedFilename(): string {
		if (!uploadInstrument) return '';
		const inst = INSTRUMENTS.find(i => i.code === uploadInstrument);
		const instName = inst ? inst.name.toLowerCase().replace(/ /g, '_') : uploadInstrument;
		const key = uploadKey || inst?.defaultKey || '';
		const keyStr = key ? `_${key}` : '';
		const clef = uploadClef ? `_${uploadClef}` : '';
		const variant = uploadVariant ? `_${uploadVariant}` : '';
		return `${instName}${variant}${keyStr}${clef}_${uploadPart}.pdf`;
	}

	let expectedFilename = $derived(getExpectedFilename());

	onMount(async () => {
		await new Promise(resolve => setTimeout(resolve, 100));
		
		const unsubscribe = auth.subscribe((state) => {
			userRole = state.user?.role || '';
		});
		
		if (userRole !== 'admin') {
			unsubscribe();
			goto('/scores');
			return;
		}
		
		await loadScores();
	});

	async function loadScores() {
		loading = true;
		try {
			const allScores = await apiService.getScores();
			// Sort by ID descending (newest first)
			scores = allScores.sort((a, b) => parseInt(b.id) - parseInt(a.id));
		} catch (err) {
			error = 'Erreur lors du chargement';
			console.error(err);
		} finally {
			loading = false;
		}
	}

	async function createScore() {
		if (!newName.trim()) return;
		saving = true;
		try {
			const pieces = newPieceNames.filter(n => n.trim()).map((name, i) => ({
				number: i + 1,
				name: name.trim() || `Partie ${i + 1}`
			}));
			const result = await apiService.createScore(newName, newCompositor, pieces);
			if (result.success) {
				showForm = false;
				newName = '';
				newCompositor = '';
				newPieceCount = 1;
				newPieceNames = [''];
				await loadScores();
			} else {
				error = result.error || 'Erreur';
			}
		} catch (err) {
			error = 'Erreur lors de la création';
			console.error(err);
		} finally {
			saving = false;
		}
	}

	async function deleteScore(id: string) {
		try {
			const result = await apiService.deleteScore(id);
			if (result.success) {
				await loadScores();
			} else {
				error = result.error || 'Erreur';
			}
		} catch (err) {
			error = 'Erreur lors de la suppression';
			console.error(err);
		}
	}

	function handleFileSelect(e: Event) {
		const target = e.target as HTMLInputElement;
		if (target.files && target.files[0]) {
			uploadFile = target.files[0];
		}
	}

	async function uploadPdf() {
		if (!uploadFile || !uploadInstrument || !uploadScoreId) {
			uploadError = 'Veuillez remplir tous les champs';
			return;
		}
		uploading = true;
		uploadError = '';
		uploadSuccess = '';
		try {
			const result = await apiService.uploadPdf(
				uploadScoreId,
				uploadFile,
				uploadPiece,
				uploadInstrument,
				uploadVersion,
				uploadKey,
				uploadClef,
				uploadVariant,
				uploadPart
			);
			if (result.success) {
				uploadSuccess = 'Fichier uploadé avec succès!';
				uploadFile = null;
			} else {
				uploadError = result.error || 'Erreur';
			}
		} catch (err) {
			uploadError = 'Erreur lors de l\'upload';
			console.error(err);
		} finally {
			uploading = false;
		}
	}
</script>

<svelte:head>
	<title>Admin - OHMJ</title>
</svelte:head>

<div class="container mx-auto px-4 py-8">
	<div class="mb-6 flex justify-between items-center">
		<h1 class="text-3xl font-bold text-ohmj-primary">Administration</h1>
		<a href="/scores" class="text-ohmj-primary hover:underline">← Retour aux partitions</a>
	</div>

	{#if !isAdmin}
		<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
			Accès refusé. Vous devez être administrateur.
		</div>
	{:else}
		<!-- Tabs -->
		<div class="mb-6 border-b">
			<nav class="flex gap-4">
				<button
					class="px-4 py-2 border-b-2 border-ohmj-primary text-ohmj-primary font-semibold"
				>
					Partitions
				</button>
			</nav>
		</div>

		{#if error}
			<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
				{error}
			</div>
		{/if}

		<!-- Create new score -->
		<div class="mb-8">
			<button
				onclick={() => { showForm = !showForm; if (!showForm) { newName = ''; newCompositor = ''; newPieceCount = 1; newPieceNames = ['']; } }}
				class="bg-ohmj-primary text-white px-4 py-2 rounded hover:bg-ohmj-secondary transition-colors"
			>
				{showForm ? 'Annuler' : '+ Nouvelle partition'}
			</button>

			{#if showForm}
				<div class="mt-4 p-4 bg-gray-50 rounded-lg">
					<form onsubmit={(e) => { e.preventDefault(); createScore(); }} class="space-y-4">
						<div>
							<label class="block text-sm font-medium text-gray-700">Nom</label>
							<input
								type="text"
								bind:value={newName}
								required
								class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-ohmj-primary focus:border-ohmj-primary"
								placeholder="Nom du morceau"
							/>
						</div>
						<div>
							<label class="block text-sm font-medium text-gray-700">Compositeur</label>
							<input
								type="text"
								bind:value={newCompositor}
								class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-ohmj-primary focus:border-ohmj-primary"
								placeholder="Compositeur (optionnel)"
							/>
						</div>
						<div>
							<label class="block text-sm font-medium text-gray-700">Nombre de parties</label>
							<select
								value={newPieceCount}
								onchange={(e) => handlePieceCountChange(parseInt((e.target as HTMLSelectElement).value))}
								class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm bg-white"
							>
								{#each [1,2,3,4,5,6,7,8,9,10] as num}
									<option value={num}>{num}</option>
								{/each}
							</select>
						</div>
						{#if newPieceCount > 1}
						<div class="space-y-2">
							<label class="block text-sm font-medium text-gray-700">Nom des parties</label>
							{#each newPieceNames as pieceName, i}
								<input
									type="text"
									bind:value={newPieceNames[i]}
									class="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-ohmj-primary focus:border-ohmj-primary"
									placeholder="Partie {i + 1}"
								/>
							{/each}
						</div>
						{/if}
						<button
							type="submit"
							disabled={saving}
							class="bg-ohmj-primary text-white px-4 py-2 rounded hover:bg-ohmj-secondary disabled:opacity-50"
						>
							{saving ? 'Création...' : 'Créer'}
						</button>
					</form>
				</div>
			{/if}
		</div>

		<!-- List of scores -->
		<div class="bg-white rounded-lg shadow overflow-hidden">
			<table class="min-w-full">
				<thead class="bg-gray-50">
					<tr>
						<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">ID</th>
						<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Nom</th>
						<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Compositeur</th>
						<th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase w-32">Actions</th>
					</tr>
				</thead>
				<tbody class="divide-y divide-gray-200">
					{#each scores as score}
						<tr class="hover:bg-gray-50">
							<td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{score.id}</td>
							<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700">{score.name}</td>
							<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{score.compositor || '-'}</td>
							<td class="px-6 py-4 whitespace-nowrap text-right text-sm">
								<div class="flex justify-end gap-3">
									<a
										href="/admin/{score.id}"
										class="text-blue-600 hover:text-blue-800"
									>
										Voir
									</a>
									<button
										onclick={() => deleteConfirmId = score.id}
										class="text-red-600 hover:text-red-800"
									>
										Supprimer
									</button>
								</div>
							</td>
						</tr>
					{/each}
				</tbody>
			</table>
		</div>
	{/if}

	{#if deleteConfirmId}
		<div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" onclick={() => deleteConfirmId = null}>
			<div class="bg-white rounded-lg shadow-xl p-6 max-w-md w-full mx-4" onclick={(e) => e.stopPropagation()}>
				<h3 class="text-lg font-semibold text-gray-900 mb-2">Confirmer la suppression</h3>
				<p class="text-gray-600 mb-6">
					Êtes-vous sûr de vouloir supprimer cette partition ? Cette action est irréversible et supprimera également tous les fichiers associés.
				</p>
				<div class="flex gap-3 justify-end">
					<button
						onclick={() => deleteConfirmId = null}
						class="px-4 py-2 text-gray-700 hover:bg-gray-100 rounded transition-colors"
					>
						Annuler
					</button>
					<button
						onclick={async () => {
							const id = deleteConfirmId;
							deleteConfirmId = null;
							if (id) await deleteScore(id);
						}}
						class="px-4 py-2 bg-red-600 text-white hover:bg-red-700 rounded transition-colors"
					>
						Supprimer
					</button>
				</div>
			</div>
		</div>
	{/if}
</div>
