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

export const load: PageServerLoad = async ({ locals, params }) => {
	// Fetch the event
	const { data: event } = await locals.supabase
		.from('events_with_counts')
		.select('*')
		.eq('id', params.id)
		.single();

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

	// Fetch all RSVPs with member details
	// Note: Using explicit foreign key reference because event_rsvps has two FKs to members (member_id, checked_in_by)
	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
			)
		`)
		.eq('event_id', params.id)
		.order('created_at', { ascending: true });

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

	// Fetch public RSVPs (non-members)
	const { data: publicRsvps } = await locals.supabase
		.from('event_rsvps_public')
		.select('*')
		.eq('event_id', params.id)
		.order('created_at', { ascending: true });

	// Calculate stats
	const memberRsvps = rsvps || [];
	const nonMemberRsvps = publicRsvps || [];

	const stats = {
		confirmed: memberRsvps.filter(r => r.status === 'confirmed').length +
			nonMemberRsvps.filter(r => r.status === 'confirmed').length,
		confirmedGuests: memberRsvps.filter(r => r.status === 'confirmed').reduce((sum, r) => sum + (r.guest_count || 0), 0) +
			nonMemberRsvps.filter(r => r.status === 'confirmed').reduce((sum, r) => sum + (r.guest_count || 0), 0),
		waitlist: memberRsvps.filter(r => r.status === 'waitlist').length +
			nonMemberRsvps.filter(r => r.status === 'waitlist').length,
		maybe: memberRsvps.filter(r => r.status === 'maybe').length,
		declined: memberRsvps.filter(r => r.status === 'declined').length +
			nonMemberRsvps.filter(r => r.status === 'declined').length,
		attended: memberRsvps.filter(r => r.attended).length +
			nonMemberRsvps.filter(r => r.attended).length,
		totalMembers: memberRsvps.length,
		totalNonMembers: nonMemberRsvps.length
	};

	stats.confirmedGuests; // Suppress unused warning

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

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

	return {
		event,
		memberRsvps,
		publicRsvps: nonMemberRsvps,
		stats,
		uninvitedMembers
	};
};

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: 'You do not have permission to check in attendees' });
		}

		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 is required' });
		}

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

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

		// Only set checked_in fields if checking in
		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: 'Failed to update attendance. Please try again.' });
		}

		return { success: attended ? 'Checked in successfully!' : 'Check-in removed.' };
	},

	updateRsvpStatus: 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 RSVPs' });
		}

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

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

		const validStatuses = ['confirmed', 'declined', 'maybe', 'waitlist', 'cancelled'];
		if (!validStatuses.includes(status)) {
			return fail(400, { error: 'Invalid status' });
		}

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

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

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

		return { success: 'RSVP status updated!' };
	},

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

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

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

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

		// Get event to check capacity
		const { data: event } = await locals.supabase
			.from('events_with_counts')
			.select('*')
			.eq('id', params.id)
			.single();

		if (!event) {
			return fail(404, { error: 'Event not found' });
		}

		// Get the RSVP to promote
		const table = isPublic ? 'event_rsvps_public' : 'event_rsvps';
		const { data: rsvp } = await locals.supabase
			.from(table)
			.select('*')
			.eq('id', rsvpId)
			.single();

		if (!rsvp) {
			return fail(404, { error: 'RSVP not found' });
		}

		if (rsvp.status !== 'waitlist') {
			return fail(400, { error: 'Only waitlisted RSVPs can be promoted' });
		}

		// Check capacity
		const spotsNeeded = 1 + (rsvp.guest_count || 0);
		if (event.max_attendees && event.total_attendees + spotsNeeded > event.max_attendees) {
			return fail(400, { error: 'Not enough capacity for this attendee and their guests' });
		}

		// Promote to confirmed
		const { error: updateError } = await locals.supabase
			.from(table)
			.update({
				status: 'confirmed',
				updated_at: new Date().toISOString()
			})
			.eq('id', rsvpId);

		if (updateError) {
			console.error('Promotion error:', updateError);
			return fail(500, { error: 'Failed to promote from waitlist. Please try again.' });
		}

		return { success: 'Successfully promoted from waitlist!' };
	},

	deleteRsvp: 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 delete RSVPs' });
		}

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

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

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

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

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

		return { success: 'RSVP removed successfully!' };
	},

	markAsPaid: 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 manage payments' });
		}

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

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

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

		const { error: updateError } = await locals.supabase
			.from(table)
			.update({
				payment_status: 'paid',
				updated_at: new Date().toISOString()
			})
			.eq('id', rsvpId);

		if (updateError) {
			console.error('Mark as paid error:', updateError);
			return fail(500, { error: 'Failed to update payment status. Please try again.' });
		}

		return { success: 'Payment marked as received!' };
	},

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

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

		const formData = await request.formData();
		const memberIds = formData.getAll('member_ids') as string[];

		if (!memberIds || memberIds.length === 0) {
			return fail(400, { error: 'Please select at least one member to invite' });
		}

		// Get the event details
		const { data: event } = await locals.supabase
			.from('events')
			.select('*')
			.eq('id', params.id)
			.single();

		if (!event) {
			return fail(404, { error: 'Event not found' });
		}

		// Get the selected members
		const { data: members } = await supabaseAdmin
			.from('members')
			.select('id, first_name, last_name, email')
			.in('id', memberIds);

		if (!members || members.length === 0) {
			return fail(400, { error: 'No valid members found' });
		}

		// Prepare email content
		const baseUrl = url.origin;
		const eventUrl = `${baseUrl}/events/${event.id}`;
		const logoUrl = `${baseUrl}/MONACOUSA-Flags_376x376.png`;

		// Format event date and time
		const eventDate = new Date(event.start_time).toLocaleDateString('en-US', {
			weekday: 'long',
			year: 'numeric',
			month: 'long',
			day: 'numeric'
		});
		const eventTime = new Date(event.start_time).toLocaleTimeString('en-US', {
			hour: 'numeric',
			minute: '2-digit'
		});

		let successCount = 0;
		let failCount = 0;

		// Send invitations to each member
		for (const invitee of members) {
			const emailResult = await sendEmail({
				to: invitee.email,
				subject: `You're Invited: ${event.title}`,
				html: `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #0f172a;">
  <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background: linear-gradient(135deg, rgba(15, 23, 42, 0.9) 0%, rgba(30, 41, 59, 0.85) 50%, rgba(127, 29, 29, 0.8) 100%); background-color: #0f172a;">
    <tr>
      <td align="center" style="padding: 40px 20px;">
        <!-- Logo Section -->
        <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="max-width: 480px;">
          <tr>
            <td align="center" style="padding-bottom: 30px;">
              <div style="background: rgba(255, 255, 255, 0.95); border-radius: 16px; padding: 12px; display: inline-block; box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);">
                <img src="${logoUrl}" alt="Monaco USA" width="80" height="80" style="display: block; border-radius: 8px;">
              </div>
              <h1 style="margin: 16px 0 4px 0; font-size: 24px; font-weight: bold; color: #ffffff; text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);">Monaco <span style="color: #fca5a5;">USA</span></h1>
              <p style="margin: 0; font-size: 14px; color: rgba(255, 255, 255, 0.8);">Americans in Monaco</p>
            </td>
          </tr>
        </table>

        <!-- Main Content Card -->
        <table role="presentation" cellspacing="0" cellpadding="0" style="max-width: 480px; width: 100%; background: #ffffff; border-radius: 16px; box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);">
          <tr>
            <td style="padding: 40px;">
              <h2 style="margin: 0 0 20px 0; color: #CE1126; font-size: 24px;">You're Invited!</h2>
              <p style="margin: 0 0 16px 0; color: #334155; line-height: 1.6;">Dear ${invitee.first_name},</p>
              <p style="margin: 0 0 20px 0; color: #334155; line-height: 1.6;">We'd love for you to join us at an upcoming Monaco USA event!</p>

              <div style="background: #f8fafc; border-radius: 12px; padding: 20px; margin: 0 0 20px 0;">
                <h3 style="margin: 0 0 12px 0; color: #CE1126; font-size: 18px;">${event.title}</h3>
                <p style="margin: 0 0 8px 0; color: #334155;"><strong>Date:</strong> ${eventDate}</p>
                <p style="margin: 0 0 8px 0; color: #334155;"><strong>Time:</strong> ${eventTime}</p>
                ${event.location ? `<p style="margin: 0; color: #334155;"><strong>Location:</strong> ${event.location}</p>` : ''}
              </div>

              ${event.description ? `<p style="margin: 0 0 20px 0; color: #334155; line-height: 1.6;">${event.description.substring(0, 200)}${event.description.length > 200 ? '...' : ''}</p>` : ''}

              <div style="text-align: center; margin: 24px 0;">
                <a href="${eventUrl}" style="display: inline-block; background: #CE1126; color: #ffffff; text-decoration: none; padding: 14px 32px; border-radius: 8px; font-weight: 600; font-size: 16px;">RSVP Now</a>
              </div>

              <p style="margin: 0; color: #64748b; font-size: 14px; text-align: center;">Click the button above to view the event details and RSVP.</p>
            </td>
          </tr>
        </table>

        <!-- Footer -->
        <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="max-width: 480px;">
          <tr>
            <td align="center" style="padding-top: 24px;">
              <p style="margin: 0; font-size: 12px; color: rgba(255, 255, 255, 0.5);">&copy; 2026 Monaco USA. All rights reserved.</p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>`,
				recipientId: invitee.id,
				recipientName: `${invitee.first_name} ${invitee.last_name}`,
				emailType: 'event_invitation',
				sentBy: member.id
			});

			if (emailResult.success) {
				successCount++;
			} else {
				failCount++;
				console.error(`Failed to send invitation to ${invitee.email}:`, emailResult.error);
			}
		}

		if (failCount === 0) {
			return { success: `Successfully sent ${successCount} invitation${successCount !== 1 ? 's' : ''}!` };
		} else if (successCount === 0) {
			return fail(500, { error: 'Failed to send all invitations. Please check your email settings.' });
		} else {
			return { success: `Sent ${successCount} invitation${successCount !== 1 ? 's' : ''}, but ${failCount} failed.` };
		}
	}
};
