<script lang="ts">
	import type { GoogleSheet } from '$lib/google/sheets/types.ts';
	
	// Props
	let { sheetsData = $bindable(), loadRecentSheets, selectSheet, toggleSheetList, resetSheetSelection } = $props<{
		sheetsData: {
			availableSheets: GoogleSheet[];
			selectedSheet: GoogleSheet | null;
			sheetData: string[][];
			columnMapping: {
				name: number;
				surname: number;
				email: number;
				confirmation: number;
			};
			loading: boolean;
			expandedSheetList: boolean;
		};
		loadRecentSheets: () => Promise<void>;
		selectSheet: (sheet: GoogleSheet) => Promise<void>;
		toggleSheetList: () => void;
		resetSheetSelection: () => void;
	}>();
	
	// Search functionality
	let searchQuery = $state('');
	let isSearching = $state(false);
	let searchResults = $state<GoogleSheet[]>([]);
	let searchError = $state('');
	
	// Debounce function for search
	function debounce(func: (...args: any[]) => void, wait: number) {
		let timeout: ReturnType<typeof setTimeout> | null = null;
		return function(...args: any[]) {
			const later = () => {
				timeout = null;
				func(...args);
			};
			if (timeout) clearTimeout(timeout);
			timeout = setTimeout(later, wait);
		};
	}
	
	// Search for sheets
	const searchSheets = debounce(async () => {
		if (!searchQuery.trim()) {
			searchResults = [];
			return;
		}
		
		isSearching = true;
		searchError = '';
		
		try {
			const response = await fetch(`/private/api/google/sheets/search?query=${encodeURIComponent(searchQuery)}`, {
				method: 'GET',
				headers: {
					Authorization: `Bearer ${localStorage.getItem('google_refresh_token')}`
				}
			});
			
			if (response.ok) {
				searchResults = await response.json();
			} else {
				searchError = 'Failed to search for sheets';
				console.error('Search error:', await response.text());
			}
		} catch (error) {
			searchError = 'Error searching for sheets';
			console.error('Search error:', error);
		} finally {
			isSearching = false;
		}
	}, 500);
	
	// Clear search
	function clearSearch() {
		searchQuery = '';
		searchResults = [];
		searchError = '';
	}
	
	$effect(() => {
		if (searchQuery) {
			searchSheets();
		} else {
			searchResults = [];
		}
	});
</script>

<div class="space-y-6">
	<div>
		<h3 class="text-lg font-medium text-gray-900 mb-4">Select Google Sheet</h3>
		
		{#if sheetsData.loading && sheetsData.availableSheets.length === 0}
			<div class="space-y-3">
				{#each Array(5) as _}
					<div class="p-4 border border-gray-200 rounded animate-pulse">
						<div class="h-4 bg-gray-200 rounded w-3/4 mb-2"></div>
						<div class="h-3 bg-gray-100 rounded w-1/2"></div>
					</div>
				{/each}
			</div>
		{:else if sheetsData.availableSheets.length === 0}
			<div class="text-center py-8">
				<p class="text-gray-500">No Google Sheets found.</p>
				<button
					onclick={loadRecentSheets}
					class="mt-2 px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition"
				>
					Refresh
				</button>
			</div>
		{:else}
			<div class="space-y-3">
				{#if !sheetsData.expandedSheetList && sheetsData.selectedSheet}
					<!-- Selected sheet only (collapsed view) -->
					<div class="flex items-center justify-between p-4 border border-blue-500 bg-blue-50 rounded">
						<div>
							<div class="font-medium text-gray-900">{sheetsData.selectedSheet.name}</div>
							<div class="text-sm text-gray-500">
								Modified: {new Date(sheetsData.selectedSheet.modifiedTime).toLocaleDateString()}
							</div>
						</div>
						<button
							onclick={resetSheetSelection}
							class="text-blue-600 hover:text-blue-800 flex items-center"
							aria-label="Reset selection and show all sheets"
						>
							<span class="text-sm mr-1">Change</span>
							<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
								<path fill-rule="evenodd" d="M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z" clip-rule="evenodd"/>
							</svg>
						</button>
					</div>
				{:else}
					<!-- All sheets and search (expanded view) -->
					<div class="flex justify-between items-center mb-2">
						<h4 class="text-sm font-medium text-gray-700">Google Sheets</h4>
						{#if sheetsData.selectedSheet}
							<button
								onclick={toggleSheetList}
								class="text-sm text-blue-600 hover:text-blue-800"
								aria-label="Hide sheet list"
							>
								Collapse list
							</button>
						{/if}
					</div>
					
					<!-- Search bar -->
					<div class="relative mb-4">
						<input
							type="text"
							bind:value={searchQuery}
							placeholder="Search all your Google Sheets..."
							class="w-full px-4 py-2 pl-10 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
						/>
						<div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
							<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
								<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
							</svg>
						</div>
						{#if searchQuery}
							<button
								onclick={clearSearch}
								class="absolute inset-y-0 right-0 pr-3 flex items-center"
								aria-label="Clear search"
							>
								<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-gray-400 hover:text-gray-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
									<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
								</svg>
							</button>
						{/if}
					</div>
					
					{#if isSearching}
						<!-- Loading state -->
						<div class="space-y-3">
							{#each Array(3) as _}
								<div class="p-4 border border-gray-200 rounded animate-pulse">
									<div class="h-4 bg-gray-200 rounded w-3/4 mb-2"></div>
									<div class="h-3 bg-gray-100 rounded w-1/2"></div>
								</div>
							{/each}
						</div>
					{:else if searchQuery && searchResults.length === 0 && !searchError}
						<!-- No search results -->
						<div class="text-center py-6 border border-gray-200 rounded">
							<p class="text-gray-500">No sheets found matching "{searchQuery}"</p>
						</div>
					{:else if searchError}
						<!-- Search error -->
						<div class="text-center py-6 border border-red-200 bg-red-50 rounded">
							<p class="text-red-600">{searchError}</p>
							<button
								onclick={searchSheets}
								class="mt-2 px-3 py-1 bg-red-600 text-white text-sm rounded hover:bg-red-700 transition"
							>
								Retry
							</button>
						</div>
					{:else if searchQuery && searchResults.length > 0}
						<!-- Search results -->
						<div class="grid gap-3">
							{#each searchResults as sheet}
								<button
									onclick={() => selectSheet(sheet)}
									class="p-4 text-left border border-gray-200 rounded hover:border-blue-500 transition {
										sheetsData.selectedSheet?.id === sheet.id ? 'border-blue-500 bg-blue-50' : ''
									}"
								>
									<div class="font-medium text-gray-900">
										{#if searchQuery}
											{#each sheet.name.split(new RegExp(`(${searchQuery})`, 'i')) as part}
												{#if part.toLowerCase() === searchQuery.toLowerCase()}
													<span class="bg-yellow-200">{part}</span>
												{:else}
													{part}
												{/if}
											{/each}
										{:else}
											{sheet.name}
										{/if}
									</div>
									<div class="text-sm text-gray-500">
										Modified: {new Date(sheet.modifiedTime).toLocaleDateString('en-GB', {day: '2-digit', month: '2-digit', year: 'numeric'})}
									</div>
								</button>
							{/each}
						</div>
					{:else}
						<!-- Recent sheets (when not searching) -->
						<div class="grid gap-3">
							{#each sheetsData.availableSheets as sheet}
								<button
									onclick={() => selectSheet(sheet)}
									class="p-4 text-left border border-gray-200 rounded hover:border-blue-500 transition {
										sheetsData.selectedSheet?.id === sheet.id ? 'border-blue-500 bg-blue-50' : ''
									}"
								>
									<div class="font-medium text-gray-900">{sheet.name}</div>
									<div class="text-sm text-gray-500">
										Modified: {new Date(sheet.modifiedTime).toLocaleDateString('en-GB', {day: '2-digit', month: '2-digit', year: 'numeric'})}
									</div>
								</button>
							{/each}
						</div>
						{#if sheetsData.availableSheets.length === 0 && !sheetsData.loading}
							<div class="text-center py-6 border border-gray-200 rounded">
								<p class="text-gray-500">No recent sheets found. Try searching above.</p>
							</div>
						{/if}
					{/if}
				{/if}
			</div>
		{/if}
	</div>

	{#if sheetsData.selectedSheet && sheetsData.sheetData.length > 0}
		<div>
			<h3 class="text-lg font-medium text-gray-900 mb-4">Column Mapping</h3>
			
			<!-- Instructions for column mapping -->
			<div class="bg-white p-4 rounded-md border border-gray-300 mb-4">
				<p class="text-sm text-black-800 mb-2 font-medium">Column Mapping Instructions:</p>
				<p class="text-sm text-black-700">
					Select what each column represents by using the dropdown in each column header. 
					Make sure to assign Name, Surname, Email, and Confirmation columns.
				</p>
			</div>
			
			<div class="overflow-x-auto">
				<table class="w-full border border-gray-200 rounded">
					<thead>
						<tr class="bg-gray-50">
							{#each sheetsData.sheetData[0] || [] as header, index}
								<th class="px-3 py-2 border-b border-gray-200 text-left">
									<div class="flex flex-col gap-2">
										<div class="font-medium text-gray-900">
											{header || `Empty Column ${index + 1}`}
										</div>
										<select 
											class="text-sm normal-case font-normal px-2 py-1 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
											aria-label={`Select data type for column ${index + 1}`}
											onclick={(e) => e.stopPropagation()}
											onchange={(e) => {
												const value = (e.target as HTMLSelectElement).value;
												if (value === "none") return;
												
												// Reset previous selection if this column was already mapped
												if (sheetsData.columnMapping.name === index + 1) sheetsData.columnMapping.name = 0;
												if (sheetsData.columnMapping.surname === index + 1) sheetsData.columnMapping.surname = 0;
												if (sheetsData.columnMapping.email === index + 1) sheetsData.columnMapping.email = 0;
												if (sheetsData.columnMapping.confirmation === index + 1) sheetsData.columnMapping.confirmation = 0;
												
												// Set new mapping
												if (value === "name") sheetsData.columnMapping.name = index + 1;
												else if (value === "surname") sheetsData.columnMapping.surname = index + 1;
												else if (value === "email") sheetsData.columnMapping.email = index + 1;
												else if (value === "confirmation") sheetsData.columnMapping.confirmation = index + 1;
											}}
										>
											<option value="none">Select data type</option>
											<option value="name" selected={sheetsData.columnMapping.name === index + 1}>Name</option>
											<option value="surname" selected={sheetsData.columnMapping.surname === index + 1}>Surname</option>
											<option value="email" selected={sheetsData.columnMapping.email === index + 1}>Email</option>
											<option value="confirmation" selected={sheetsData.columnMapping.confirmation === index + 1}>Confirmation</option>
										</select>
										<div class="h-7 mt-1"> <!-- Fixed height container to prevent layout shift -->
											{#if sheetsData.columnMapping.name === index + 1}
												<span class="bg-green-100 text-green-800 text-xs px-2 py-1 rounded">Name Column</span>
											{:else if sheetsData.columnMapping.surname === index + 1}
												<span class="bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded">Surname Column</span>
											{:else if sheetsData.columnMapping.email === index + 1}
												<span class="bg-purple-100 text-purple-800 text-xs px-2 py-1 rounded">Email Column</span>
											{:else if sheetsData.columnMapping.confirmation === index + 1}
												<span class="bg-amber-100 text-amber-800 text-xs px-2 py-1 rounded">Confirmation Column</span>
											{:else}
												<span class="bg-gray-100 text-gray-400 text-xs px-2 py-1 rounded">Not Mapped</span>
											{/if}
										</div>
									</div>
								</th>
							{/each}
						</tr>
					</thead>
					<tbody>
						{#each sheetsData.sheetData.slice(0, 10) as row, rowIndex}
							<tr class="hover:bg-gray-50">
								{#each row as cell, cellIndex}
									<td class="px-3 py-2 border-b border-gray-100 text-sm">
										<span 
											class={
												sheetsData.columnMapping.name === cellIndex + 1 ? 'font-medium text-green-700' : 
												sheetsData.columnMapping.surname === cellIndex + 1 ? 'font-medium text-blue-700' : 
												sheetsData.columnMapping.email === cellIndex + 1 ? 'font-medium text-purple-700' : 
												sheetsData.columnMapping.confirmation === cellIndex + 1 ? 'font-medium text-amber-700' : 
												'text-gray-700'
											}
											title={cell || ''}
										>
											{cell || ''}
										</span>
									</td>
								{/each}
							</tr>
						{/each}
					</tbody>
				</table>
			</div>
			<div class="flex justify-between mt-2">
				<p class="text-sm text-gray-500">Showing first 10 rows</p>
				{#if sheetsData.sheetData[0] && sheetsData.sheetData[0].length > 3}
					<p class="text-sm text-gray-500">
						<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 inline mr-1" viewBox="0 0 20 20" fill="currentColor">
							<path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd" />
						</svg>
						Scroll horizontally to see all {sheetsData.sheetData[0].length} columns
					</p>
				{/if}
			</div>
		</div>
	{/if}

	{#if sheetsData.loading && sheetsData.selectedSheet}
		<div class="text-center py-4">
			<div class="text-gray-600">Loading sheet data...</div>
		</div>
	{/if}
</div>


