import { fail } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ locals, url }) => {
	const statusFilter = url.searchParams.get('status') || 'all';

	// Load events with counts
	let query = locals.supabase
		.from('events_with_counts')
		.select('*')
		.order('start_datetime', { ascending: true });

	if (statusFilter !== 'all') {
		query = query.eq('status', statusFilter);
	}

	const { data: events } = await query;

	// Load event types
	const { data: eventTypes } = await locals.supabase
		.from('event_types')
		.select('*')
		.eq('is_active', true)
		.order('sort_order', { ascending: true });

	// Calculate stats
	const now = new Date();
	const stats = {
		total: events?.length || 0,
		upcoming: events?.filter((e: any) => new Date(e.start_datetime) > now && e.status === 'published').length || 0,
		draft: events?.filter((e: any) => e.status === 'draft').length || 0,
		past: events?.filter((e: any) => new Date(e.end_datetime) < now).length || 0
	};

	return {
		events: events || [],
		eventTypes: eventTypes || [],
		stats,
		filters: {
			status: statusFilter
		}
	};
};

export const actions: Actions = {
	create: async ({ request, locals }) => {
		const { member } = await locals.safeGetSession();

		if (!member || (member.role !== 'board' && member.role !== 'admin')) {
			return fail(403, { error: 'You do not have permission to create events' });
		}

		const formData = await request.formData();

		const title = formData.get('title') as string;
		const description = formData.get('description') as string;
		const eventTypeId = formData.get('event_type_id') as string;
		const startDate = formData.get('start_date') as string;
		const startTime = formData.get('start_time') as string;
		const endDate = formData.get('end_date') as string;
		const endTime = formData.get('end_time') as string;
		const location = formData.get('location') as string;
		const maxAttendees = formData.get('max_attendees') as string;
		const maxGuests = formData.get('max_guests_per_member') as string;
		const isPaid = formData.get('is_paid') === 'true';
		const memberPrice = formData.get('member_price') as string;
		const nonMemberPrice = formData.get('non_member_price') as string;
		const visibility = formData.get('visibility') as string;
		const status = formData.get('status') as string;

		// Validation
		if (!title || !startDate || !startTime || !endDate || !endTime) {
			return fail(400, { error: 'Title, start date/time, and end date/time are required' });
		}

		// Construct datetime strings
		const startDatetime = `${startDate}T${startTime}:00`;
		const endDatetime = `${endDate}T${endTime}:00`;

		// Validate end is after start
		if (new Date(endDatetime) <= new Date(startDatetime)) {
			return fail(400, { error: 'End date/time must be after start date/time' });
		}

		const { error: insertError } = await locals.supabase.from('events').insert({
			title,
			description: description || null,
			event_type_id: eventTypeId || null,
			start_datetime: startDatetime,
			end_datetime: endDatetime,
			location: location || null,
			max_attendees: maxAttendees ? parseInt(maxAttendees) : null,
			max_guests_per_member: maxGuests ? parseInt(maxGuests) : 1,
			is_paid: isPaid,
			member_price: isPaid && memberPrice ? parseFloat(memberPrice) : 0,
			non_member_price: isPaid && nonMemberPrice ? parseFloat(nonMemberPrice) : 0,
			visibility: visibility || 'members',
			status: status || 'published',
			created_by: member.id
		});

		if (insertError) {
			console.error('Event creation error:', insertError);
			return fail(500, { error: 'Failed to create event. Please try again.' });
		}

		return { success: 'Event created successfully!' };
	},

	delete: async ({ request, locals }) => {
		const { member } = await locals.safeGetSession();

		if (!member || member.role !== 'admin') {
			return fail(403, { error: 'Only admins can delete events' });
		}

		const formData = await request.formData();
		const eventId = formData.get('event_id') as string;

		if (!eventId) {
			return fail(400, { error: 'Event ID is required' });
		}

		const { error: deleteError } = await locals.supabase.from('events').delete().eq('id', eventId);

		if (deleteError) {
			console.error('Event deletion error:', deleteError);
			return fail(500, { error: 'Failed to delete event. Please try again.' });
		}

		return { success: 'Event deleted successfully!' };
	},

	updateStatus: async ({ request, locals }) => {
		const { member } = await locals.safeGetSession();

		if (!member || (member.role !== 'board' && member.role !== 'admin')) {
			return fail(403, { error: 'You do not have permission to update events' });
		}

		const formData = await request.formData();
		const eventId = formData.get('event_id') as string;
		const status = formData.get('status') as string;

		if (!eventId || !status) {
			return fail(400, { error: 'Event ID and status are required' });
		}

		const { error: updateError } = await locals.supabase
			.from('events')
			.update({ status, updated_at: new Date().toISOString() })
			.eq('id', eventId);

		if (updateError) {
			console.error('Event status update error:', updateError);
			return fail(500, { error: 'Failed to update event status. Please try again.' });
		}

		return { success: 'Event status updated!' };
	}
};
