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

export const load: PageServerLoad = async ({ locals }) => {
	const { session } = await locals.safeGetSession();

	// If already logged in, redirect to dashboard
	if (session) {
		throw redirect(303, '/dashboard');
	}

	return {};
};

export const actions: Actions = {
	default: async ({ request, locals, url }) => {
		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 phone = formData.get('phone') as string;
		const dateOfBirth = formData.get('date_of_birth') as string;
		const address = formData.get('address') as string;
		const nationalityString = formData.get('nationality') as string;
		const password = formData.get('password') as string;
		const confirmPassword = formData.get('confirm_password') as string;
		const terms = formData.get('terms');

		// 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 (!phone) {
			errors.phone = 'Phone number is required';
		}

		if (!dateOfBirth) {
			errors.date_of_birth = 'Date of birth is required';
		} else {
			// Check if 18+
			const birthDate = new Date(dateOfBirth);
			const today = new Date();
			const age = today.getFullYear() - birthDate.getFullYear();
			const monthDiff = today.getMonth() - birthDate.getMonth();
			const dayDiff = today.getDate() - birthDate.getDate();
			const actualAge = monthDiff < 0 || (monthDiff === 0 && dayDiff < 0) ? age - 1 : age;

			if (actualAge < 18) {
				errors.date_of_birth = 'You must be at least 18 years old to join';
			}
		}

		if (!address || address.length < 10) {
			errors.address = 'Please enter a complete address';
		}

		const nationality = nationalityString ? nationalityString.split(',').filter(Boolean) : [];
		if (nationality.length === 0) {
			errors.nationality = 'Please select at least one nationality';
		}

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

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

		if (!terms) {
			errors.terms = 'You must accept the terms and conditions';
		}

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

		// Create Supabase auth user
		const { data: authData, error: authError } = await locals.supabase.auth.signUp({
			email,
			password,
			options: {
				emailRedirectTo: `${url.origin}/auth/callback`,
				data: {
					first_name: firstName,
					last_name: lastName
				}
			}
		});

		if (authError) {
			if (authError.message.includes('already registered')) {
				return fail(400, {
					error: 'An account with this email already exists. Try signing in instead.',
					first_name: firstName,
					last_name: lastName,
					email,
					phone,
					date_of_birth: dateOfBirth,
					address
				});
			}

			return fail(400, {
				error: authError.message,
				first_name: firstName,
				last_name: lastName,
				email,
				phone,
				date_of_birth: dateOfBirth,
				address
			});
		}

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

		// Get the default membership status (pending)
		const { data: defaultStatus, error: statusError } = await locals.supabase
			.from('membership_statuses')
			.select('id')
			.eq('is_default', true)
			.single();

		// Get the default membership type
		const { data: defaultType, error: typeError } = await locals.supabase
			.from('membership_types')
			.select('id')
			.eq('is_default', true)
			.single();

		// Validate that default status and type exist
		if (statusError || !defaultStatus?.id) {
			console.error('No default membership status found:', statusError);
			// Clean up the auth user since we can't complete registration
			await supabaseAdmin.auth.admin.deleteUser(authData.user.id);
			return fail(500, {
				error: 'System configuration error. Please contact support.',
				first_name: firstName,
				last_name: lastName,
				email,
				phone,
				date_of_birth: dateOfBirth,
				address
			});
		}

		if (typeError || !defaultType?.id) {
			console.error('No default membership type found:', typeError);
			// Clean up the auth user since we can't complete registration
			await supabaseAdmin.auth.admin.deleteUser(authData.user.id);
			return fail(500, {
				error: 'System configuration error. Please contact support.',
				first_name: firstName,
				last_name: lastName,
				email,
				phone,
				date_of_birth: dateOfBirth,
				address
			});
		}

		// Create member profile
		const { error: memberError } = await locals.supabase.from('members').insert({
			id: authData.user.id,
			first_name: firstName,
			last_name: lastName,
			email,
			phone,
			date_of_birth: dateOfBirth,
			address,
			nationality,
			role: 'member',
			membership_status_id: defaultStatus.id,
			membership_type_id: defaultType.id
		});

		if (memberError) {
			// Clean up the auth user since member profile creation failed
			console.error('Failed to create member profile:', memberError);
			try {
				await supabaseAdmin.auth.admin.deleteUser(authData.user.id);
			} catch (deleteError) {
				console.error('Failed to clean up auth user:', deleteError);
			}
			return fail(500, {
				error: 'Failed to create member profile. Please try again or contact support.',
				first_name: firstName,
				last_name: lastName,
				email,
				phone,
				date_of_birth: dateOfBirth,
				address
			});
		}

		// Return success - user needs to verify email
		return {
			success:
				'Account created! Please check your email to verify your account before signing in.'
		};
	}
};
