import { fail, redirect } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
import { supabaseAdmin } from '$lib/server/supabase';
import { sendEmail, wrapInMonacoTemplate } from '$lib/server/email';
import { invalidateSetupCache } from '../../hooks.server';

export const load: PageServerLoad = async () => {
	// Check if any users exist in the system
	const { count, error } = await supabaseAdmin
		.from('members')
		.select('*', { count: 'exact', head: true });

	if (error) {
		console.error('Error checking for existing users:', error);
		// If we can't check, assume setup is needed (will fail gracefully later)
		return { needsSetup: true };
	}

	// If users already exist, redirect to login
	if (count && count > 0) {
		throw redirect(303, '/login');
	}

	return { needsSetup: true };
};

export const actions: Actions = {
	default: async ({ request, url }) => {
		// Double-check that no users exist (prevent race conditions)
		const { count: existingCount } = await supabaseAdmin
			.from('members')
			.select('*', { count: 'exact', head: true });

		if (existingCount && existingCount > 0) {
			return fail(400, {
				error: 'Setup has already been completed. Please sign in instead.'
			});
		}

		const formData = await request.formData();

		// Extract form fields
		const firstName = formData.get('first_name') as string;
		const lastName = formData.get('last_name') as string;
		const email = formData.get('email') as string;
		const password = formData.get('password') as string;
		const confirmPassword = formData.get('confirm_password') as string;

		// Validation
		const errors: Record<string, string> = {};

		if (!firstName || firstName.length < 2) {
			errors.first_name = 'First name must be at least 2 characters';
		}

		if (!lastName || lastName.length < 2) {
			errors.last_name = 'Last name must be at least 2 characters';
		}

		if (!email || !email.includes('@')) {
			errors.email = 'Please enter a valid email address';
		}

		if (!password || password.length < 8) {
			errors.password = 'Password must be at least 8 characters';
		}

		if (password !== confirmPassword) {
			errors.confirm_password = 'Passwords do not match';
		}

		// Return validation errors
		if (Object.keys(errors).length > 0) {
			return fail(400, {
				error: Object.values(errors)[0],
				first_name: firstName,
				last_name: lastName,
				email
			});
		}

		// Create user with admin service role (auto-confirms email)
		const { data: authData, error: authError } = await supabaseAdmin.auth.admin.createUser({
			email,
			password,
			email_confirm: true, // Auto-confirm email for initial admin
			user_metadata: {
				first_name: firstName,
				last_name: lastName
			}
		});

		if (authError) {
			console.error('Failed to create admin user:', authError);
			return fail(400, {
				error: authError.message,
				first_name: firstName,
				last_name: lastName,
				email
			});
		}

		if (!authData.user) {
			return fail(500, {
				error: 'Failed to create admin account. Please try again.',
				first_name: firstName,
				last_name: lastName,
				email
			});
		}

		// Get or create default membership status (active for admin)
		let statusId: string;
		const { data: activeStatus } = await supabaseAdmin
			.from('membership_statuses')
			.select('id')
			.eq('name', 'Active')
			.single();

		if (activeStatus) {
			statusId = activeStatus.id;
		} else {
			// Create active status if it doesn't exist
			const { data: newStatus, error: statusError } = await supabaseAdmin
				.from('membership_statuses')
				.insert({
					name: 'Active',
					display_name: 'Active',
					description: 'Active member in good standing',
					is_default: false,
					color: '#22c55e'
				})
				.select('id')
				.single();

			if (statusError || !newStatus) {
				console.error('Failed to create membership status:', statusError);
				await supabaseAdmin.auth.admin.deleteUser(authData.user.id);
				return fail(500, {
					error: 'Failed to set up membership status. Please try again.',
					first_name: firstName,
					last_name: lastName,
					email
				});
			}
			statusId = newStatus.id;
		}

		// Get or create default membership type
		let typeId: string;
		const { data: defaultType } = await supabaseAdmin
			.from('membership_types')
			.select('id')
			.eq('is_default', true)
			.single();

		if (defaultType) {
			typeId = defaultType.id;
		} else {
			// Create default membership type if it doesn't exist
			const { data: newType, error: typeError } = await supabaseAdmin
				.from('membership_types')
				.insert({
					name: 'Standard',
					description: 'Standard membership',
					annual_dues: 0,
					is_default: true
				})
				.select('id')
				.single();

			if (typeError || !newType) {
				console.error('Failed to create membership type:', typeError);
				await supabaseAdmin.auth.admin.deleteUser(authData.user.id);
				return fail(500, {
					error: 'Failed to set up membership type. Please try again.',
					first_name: firstName,
					last_name: lastName,
					email
				});
			}
			typeId = newType.id;
		}

		// Create admin member profile
		const { error: memberError } = await supabaseAdmin.from('members').insert({
			id: authData.user.id,
			first_name: firstName,
			last_name: lastName,
			email,
			role: 'admin', // Set as admin
			membership_status_id: statusId,
			membership_type_id: typeId,
			nationality: ['US'] // Default nationality
		});

		if (memberError) {
			console.error('Failed to create admin member profile:', memberError);
			await supabaseAdmin.auth.admin.deleteUser(authData.user.id);
			return fail(500, {
				error: 'Failed to create admin profile. Please try again.',
				first_name: firstName,
				last_name: lastName,
				email
			});
		}

		// Send welcome email to admin
		try {
			const portalUrl = url.origin;
			const welcomeContent = `
				<p style="margin: 0 0 16px 0; color: #334155; line-height: 1.6;">
					Welcome, ${firstName}!
				</p>
				<p style="margin: 0 0 16px 0; color: #334155; line-height: 1.6;">
					Congratulations! You've successfully set up the Monaco USA Portal as the founding administrator.
				</p>
				<p style="margin: 0 0 16px 0; color: #334155; line-height: 1.6;">
					As the admin, you can now:
				</p>
				<ul style="margin: 0 0 20px 0; padding-left: 24px; color: #334155; line-height: 1.8;">
					<li>Invite new members to join the portal</li>
					<li>Manage membership statuses and types</li>
					<li>Create and manage events</li>
					<li>Configure organization settings</li>
					<li>Set up email and storage integrations</li>
				</ul>
				<div style="text-align: center; margin: 24px 0;">
					<a href="${portalUrl}/login" style="display: inline-block; background: #CE1126; color: white; text-decoration: none; padding: 12px 32px; border-radius: 8px; font-weight: 600;">Sign In to Portal</a>
				</div>
				<p style="margin: 20px 0 0 0; color: #64748b; font-size: 14px;">
					If you have any questions, please reach out to the development team.
				</p>
			`;

			await sendEmail({
				to: email,
				subject: 'Welcome to Monaco USA Portal - Admin Setup Complete',
				html: wrapInMonacoTemplate({
					title: 'Welcome, Administrator!',
					content: welcomeContent
				}),
				recipientId: authData.user.id,
				recipientName: `${firstName} ${lastName}`,
				emailType: 'welcome',
				sentBy: 'system'
			});
		} catch (emailError) {
			console.error('Failed to send admin welcome email:', emailError);
			// Non-critical - continue anyway since the account was created successfully
		}

		// Clear the setup cache so other routes don't redirect back to /setup
		invalidateSetupCache();

		// Success - redirect to login
		throw redirect(303, '/login?setup=complete');
	}
};
