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

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

	// Only board and admin can access roll call
	if (!member || (member.role !== 'board' && member.role !== 'admin')) {
		throw redirect(303, `/board/events/${params.id}`);
	}

	// Fetch the event
	const { data: event, error: eventError } = await locals.supabase
		.from('events_with_counts')
		.select('*')
		.eq('id', params.id)
		.single();

	if (eventError || !event) {
		throw error(404, 'Event not found');
	}

	// Fetch all RSVPs with member details (only confirmed status for roll call)
	const { data: rsvps, error: rsvpError } = await locals.supabase
		.from('event_rsvps')
		.select(`
			*,
			member:members!event_rsvps_member_id_fkey(
				id,
				first_name,
				last_name,
				email,
				phone,
				member_id,
				avatar_url
			)
		`)
		.eq('event_id', params.id)
		.in('status', ['confirmed', 'waitlist'])
		.order('created_at', { ascending: true });

	if (rsvpError) {
		console.error('RSVP fetch error:', rsvpError);
	}

	// Fetch public RSVPs (non-members with confirmed status)
	const { data: publicRsvps, error: publicError } = await locals.supabase
		.from('event_rsvps_public')
		.select('*')
		.eq('event_id', params.id)
		.in('status', ['confirmed', 'waitlist'])
		.order('created_at', { ascending: true });

	if (publicError) {
		console.error('Public RSVP fetch error:', publicError);
	}

	// Calculate stats
	const allMemberRsvps = rsvps || [];
	const allPublicRsvps = publicRsvps || [];
	const allRsvps = [...allMemberRsvps, ...allPublicRsvps];

	const stats = {
		total: allRsvps.length,
		confirmed: allRsvps.filter(r => r.status === 'confirmed').length,
		checkedIn: allRsvps.filter(r => r.attended).length,
		waitlist: allRsvps.filter(r => r.status === 'waitlist').length
	};

	// Get all members for walk-in feature
	const { data: allMembers } = await supabaseAdmin
		.from('members')
		.select('id, first_name, last_name, email, member_id, avatar_url')
		.order('first_name', { ascending: true });

	// Filter out members who have already RSVPed
	const rsvpedMemberIds = new Set(allMemberRsvps.map(r => r.member_id));
	const availableMembers = (allMembers || []).filter(m => !rsvpedMemberIds.has(m.id));

	return {
		event,
		memberRsvps: allMemberRsvps,
		publicRsvps: allPublicRsvps,
		stats,
		availableMembers
	};
};

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

		if (!member || (member.role !== 'board' && member.role !== 'admin')) {
			return fail(403, { error: 'Permission denied' });
		}

		const formData = await request.formData();
		const rsvpId = formData.get('rsvp_id') as string;
		const isPublic = formData.get('is_public') === 'true';
		const attended = formData.get('attended') === 'true';

		if (!rsvpId) {
			return fail(400, { error: 'RSVP ID required' });
		}

		const table = isPublic ? 'event_rsvps_public' : 'event_rsvps';

		const updateData: Record<string, unknown> = {
			attended,
			updated_at: new Date().toISOString()
		};

		if (attended) {
			updateData.checked_in_at = new Date().toISOString();
			if (!isPublic) {
				updateData.checked_in_by = member.id;
			}
		} else {
			updateData.checked_in_at = null;
			if (!isPublic) {
				updateData.checked_in_by = null;
			}
		}

		const { error: updateError } = await locals.supabase
			.from(table)
			.update(updateData)
			.eq('id', rsvpId);

		if (updateError) {
			console.error('Check-in error:', updateError);
			return fail(500, { error: 'Check-in failed' });
		}

		return { success: true, attended };
	},

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

		if (!member || (member.role !== 'board' && member.role !== 'admin')) {
			return fail(403, { error: 'Permission denied' });
		}

		const formData = await request.formData();
		const memberId = formData.get('member_id') as string;
		const guestName = formData.get('guest_name') as string;
		const guestEmail = formData.get('guest_email') as string;

		const eventId = params.id;

		// If it's an existing member
		if (memberId) {
			// Check if member already has an RSVP
			const { data: existing } = await locals.supabase
				.from('event_rsvps')
				.select('id')
				.eq('event_id', eventId)
				.eq('member_id', memberId)
				.single();

			if (existing) {
				return fail(400, { error: 'Member already has an RSVP for this event' });
			}

			// Create RSVP with immediate check-in
			const { error: insertError } = await locals.supabase
				.from('event_rsvps')
				.insert({
					event_id: eventId,
					member_id: memberId,
					status: 'confirmed',
					attended: true,
					checked_in_at: new Date().toISOString(),
					checked_in_by: member.id,
					rsvp_source: 'walk_in',
					created_at: new Date().toISOString(),
					updated_at: new Date().toISOString()
				});

			if (insertError) {
				console.error('Walk-in RSVP error:', insertError);
				return fail(500, { error: 'Failed to add walk-in' });
			}

			return { success: true, message: 'Member added as walk-in' };
		}

		// If it's a non-member guest
		if (guestName) {
			const { error: insertError } = await locals.supabase
				.from('event_rsvps_public')
				.insert({
					event_id: eventId,
					full_name: guestName,
					email: guestEmail || null,
					status: 'confirmed',
					attended: true,
					checked_in_at: new Date().toISOString(),
					created_at: new Date().toISOString(),
					updated_at: new Date().toISOString()
				});

			if (insertError) {
				console.error('Walk-in guest error:', insertError);
				return fail(500, { error: 'Failed to add guest' });
			}

			return { success: true, message: 'Guest added as walk-in' };
		}

		return fail(400, { error: 'Please provide a member or guest information' });
	},

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

		if (!member || (member.role !== 'board' && member.role !== 'admin')) {
			return fail(403, { error: 'Permission denied' });
		}

		const formData = await request.formData();
		const rsvpIdsString = formData.get('rsvp_ids') as string;
		const isPublicString = formData.get('is_public_ids') as string;
		const attended = formData.get('attended') === 'true';

		if (!rsvpIdsString) {
			return fail(400, { error: 'No RSVPs selected' });
		}

		const rsvpIds = rsvpIdsString.split(',');
		const isPublicIds = isPublicString ? isPublicString.split(',') : [];

		const updateData: Record<string, unknown> = {
			attended,
			updated_at: new Date().toISOString()
		};

		if (attended) {
			updateData.checked_in_at = new Date().toISOString();
		} else {
			updateData.checked_in_at = null;
		}

		// Update member RSVPs
		const memberRsvpIds = rsvpIds.filter(id => !isPublicIds.includes(id));
		const publicRsvpIds = rsvpIds.filter(id => isPublicIds.includes(id));

		if (memberRsvpIds.length > 0) {
			const memberUpdateData = { ...updateData };
			if (attended) {
				memberUpdateData.checked_in_by = member.id;
			} else {
				memberUpdateData.checked_in_by = null;
			}

			const { error: memberError } = await locals.supabase
				.from('event_rsvps')
				.update(memberUpdateData)
				.in('id', memberRsvpIds);

			if (memberError) {
				console.error('Bulk member check-in error:', memberError);
			}
		}

		if (publicRsvpIds.length > 0) {
			const { error: publicError } = await locals.supabase
				.from('event_rsvps_public')
				.update(updateData)
				.in('id', publicRsvpIds);

			if (publicError) {
				console.error('Bulk public check-in error:', publicError);
			}
		}

		return { success: true, count: rsvpIds.length };
	}
};
