<script lang="ts">
	import { onMount } from 'svelte';
	import type { GoogleSheet } from '$lib/google/sheets/types.ts';
	import { goto } from '$app/navigation';
	import { toast } from '$lib/stores/toast.js';

	// Import Components
	import GoogleAuthStep from './components/GoogleAuthStep.svelte';
	import EventDetailsStep from './components/EventDetailsStep.svelte';
	import GoogleSheetsStep from './components/GoogleSheetsStep.svelte';
	import EmailSettingsStep from './components/EmailSettingsStep.svelte';
	import StepNavigator from './components/StepNavigator.svelte';
	import StepNavigation from './components/StepNavigation.svelte';

	let { data } = $props();

	// Step management
	let currentStep = $state(0);
	const totalSteps = 4;

	// Step 0: Google Auth
	let isGoogleConnected = $state(false);

	// Step 1: Event Details
	let eventData = $state({
		name: '',
		date: ''
	});

	// Step 2: Google Sheets
	let sheetsData = $state({
		availableSheets: [] as GoogleSheet[],
		selectedSheet: null as GoogleSheet | null,
		sheetData: [] as string[][],
		columnMapping: {
			name: 0,
			surname: 0,
			email: 0,
			confirmation: 0
		},
		loading: false,
		expandedSheetList: true
	});

	// Step 3: Email
	let emailData = $state({
		subject: '',
		body: ''
	});

	// General state
	let loading = $state(false);
	let errors = $state<Record<string, string>>({});

	onMount(async () => {
		if (currentStep === 2) {
			await loadRecentSheets();
		}
	});

	// Step navigation
	function nextStep() {
		if (validateCurrentStep()) {
			currentStep = Math.min(currentStep + 1, totalSteps - 1);
			if (currentStep === 2) {
				loadRecentSheets();
			}
		}
	}

	function prevStep() {
		currentStep = Math.max(currentStep - 1, 0);
	}

	function validateCurrentStep(): boolean {
		// Clear previous errors
		errors = {};
		let isValid = true;

		if (currentStep === 0) {
			if (!isGoogleConnected) {
				toast.error('Please connect your Google account to continue');
				errors.auth = 'Please connect your Google account to continue';
				return false;
			}
		} else if (currentStep === 1) {
			if (!eventData.name.trim()) {
				toast.error('Event name is required');
				errors.name = 'Event name is required';
				isValid = false;
			}
			if (!eventData.date) {
				toast.error('Event date is required');
				errors.date = 'Event date is required';
				isValid = false;
			}
		} else if (currentStep === 2) {
			if (!sheetsData.selectedSheet) {
				toast.error('Please select a Google Sheet');
				errors.sheet = 'Please select a Google Sheet';
				isValid = false;
			}

			if (sheetsData.selectedSheet) {
				// Validate column mappings
				const { name, surname, email, confirmation } = sheetsData.columnMapping;
				const missingColumns = [];

				if (!name) missingColumns.push('Name');
				if (!surname) missingColumns.push('Surname');
				if (!email) missingColumns.push('Email');
				if (!confirmation) missingColumns.push('Confirmation');

				if (missingColumns.length > 0) {
					const errorMsg = `Please map the following columns: ${missingColumns.join(', ')}`;
					toast.error(errorMsg);
					errors.sheetData = errorMsg;
					isValid = false;
				}
			}
		} else if (currentStep === 3) {
			if (!emailData.subject.trim()) {
				toast.error('Email subject is required');
				errors.subject = 'Email subject is required';
				isValid = false;
			}
			if (!emailData.body.trim()) {
				toast.error('Email body is required');
				errors.body = 'Email body is required';
				isValid = false;
			}
		}

		return isValid;
	}

	// Google Sheets functions
	async function loadRecentSheets() {
		sheetsData.loading = true;
		// Always expand the sheet list when loading new sheets
		sheetsData.expandedSheetList = true;

		try {
			// Use the new unified API endpoint
			const response = await fetch('/private/api/google/sheets/recent', {
				method: 'GET',
				headers: {
					Authorization: `Bearer ${localStorage.getItem('google_refresh_token')}`
				}
			});

			if (response.ok) {
				sheetsData.availableSheets = await response.json();
			}
		} catch (error) {
			console.error('Error loading sheets:', error);
			errors.sheets = 'Failed to load Google Sheets';
		} finally {
			sheetsData.loading = false;
		}
	}

	async function selectSheet(sheet: GoogleSheet) {
		const sameSheet = sheetsData.selectedSheet?.id === sheet.id;

		sheetsData.selectedSheet = sheet;
		sheetsData.loading = true;

		// Collapse sheet list when selecting a new sheet
		if (!sameSheet) {
			sheetsData.expandedSheetList = false;
		}

		try {
			// Use the new unified API endpoint, requesting only a preview range
			const response = await fetch(`/private/api/google/sheets/${sheet.id}/data?range=A1:Z10`, {
				method: 'GET',
				headers: {
					Authorization: `Bearer ${localStorage.getItem('google_refresh_token')}`
				}
			});

			if (response.ok) {
				const data = await response.json();
				sheetsData.sheetData = data.values || [];
			}
		} catch (error) {
			console.error('Error loading sheet data:', error);
			errors.sheetData = 'Failed to load sheet data';
		} finally {
			sheetsData.loading = false;
		}
	}

	// Toggle the sheet list expansion
	function toggleSheetList() {
		sheetsData.expandedSheetList = !sheetsData.expandedSheetList;
	}

	// Reset sheet selection and show sheet list
	function resetSheetSelection() {
		sheetsData.selectedSheet = null;
		sheetsData.sheetData = [];
		sheetsData.columnMapping = {
			name: 0,
			surname: 0,
			email: 0,
			confirmation: 0
		};
		sheetsData.expandedSheetList = true;
	}

	// Final submission
	async function createEvent() {
		if (!validateCurrentStep()) return;

		loading = true;
		try {
			const { data: newEvent, error } = await data.supabase.rpc('create_event', {
				p_name: eventData.name,
				p_date: eventData.date,
				p_email_subject: emailData.subject,
				p_email_body: emailData.body,
				p_sheet_id: sheetsData.selectedSheet?.id,
				p_name_column: sheetsData.columnMapping.name,
				p_surname_column: sheetsData.columnMapping.surname,
				p_email_column: sheetsData.columnMapping.email,
				p_confirmation_column: sheetsData.columnMapping.confirmation
			});

			if (error) throw error;

			// Display success message
			toast.success(`Event "${eventData.name}" was created successfully`);

			// Redirect to the event view page using the returned event ID
			if (newEvent) {
				goto(`/private/events/event/view?id=${newEvent.id}`);
			} else {
				// Fallback to events list if for some reason the event ID wasn't returned
				goto('/private/events');
			}
		} catch (error) {
			console.error('Error creating event:', error);
			toast.error('Failed to create event. Please try again.');
		} finally {
			loading = false;
		}
	}

	// Computed values
	let canProceed = $derived(() => {
		if (currentStep === 0) return isGoogleConnected;
		if (currentStep === 1) return !!(eventData.name && eventData.date);
		if (currentStep === 2) {
			const { name, surname, email, confirmation } = sheetsData.columnMapping;
			return !!(sheetsData.selectedSheet && name && surname && email && confirmation);
		}
		if (currentStep === 3) return !!(emailData.subject && emailData.body);
		return false;
	});
</script>

<!-- Header -->
<StepNavigator {currentStep} {totalSteps} />

<!-- Step Content -->
<div class="mb-4 rounded border border-gray-300 bg-white p-6">
	{#if currentStep === 0}
		<GoogleAuthStep
			onSuccess={() => (isGoogleConnected = true)}
			onDisconnect={() => (isGoogleConnected = false)}
			onError={(err) => toast.error(err)}
		/>
	{:else if currentStep === 1}
		<EventDetailsStep bind:eventData />
	{:else if currentStep === 2}
		<GoogleSheetsStep
			bind:sheetsData
			{loadRecentSheets}
			{selectSheet}
			{toggleSheetList}
			{resetSheetSelection}
		/>
	{:else if currentStep === 3}
		<EmailSettingsStep bind:emailData />
	{/if}
</div>

<!-- Navigation -->
<StepNavigation
	{currentStep}
	{totalSteps}
	canProceed={canProceed()}
	{loading}
	{prevStep}
	{nextStep}
	{createEvent}
/>
