import type { PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ locals, url }) => {
	const reportType = url.searchParams.get('type') || 'membership';
	const year = parseInt(url.searchParams.get('year') || new Date().getFullYear().toString());

	// Get all members with dues info
	const { data: members } = await locals.supabase
		.from('members_with_dues')
		.select('*')
		.order('last_name', { ascending: true });

	// Get all payments for the year
	const startOfYear = new Date(year, 0, 1).toISOString();
	const endOfYear = new Date(year, 11, 31, 23, 59, 59).toISOString();

	const { data: payments } = await locals.supabase
		.from('dues_payments')
		.select(`
			*,
			member:members(first_name, last_name, email, member_id)
		`)
		.gte('payment_date', startOfYear)
		.lte('payment_date', endOfYear)
		.order('payment_date', { ascending: false });

	// Get all events for the year with attendance data
	const { data: events } = await locals.supabase
		.from('events_with_counts')
		.select('*')
		.gte('start_datetime', startOfYear)
		.lte('start_datetime', endOfYear)
		.order('start_datetime', { ascending: false });

	// Get event RSVPs for attendance report
	const { data: rsvps } = await locals.supabase
		.from('event_rsvps')
		.select(`
			*,
			event:events(title, start_datetime),
			member:members(first_name, last_name, email)
		`)
		.eq('status', 'confirmed');

	// Calculate membership statistics
	const membershipStats = {
		total: members?.length || 0,
		byStatus: {} as Record<string, number>,
		byRole: {
			admin: members?.filter(m => m.role === 'admin').length || 0,
			board: members?.filter(m => m.role === 'board').length || 0,
			member: members?.filter(m => m.role === 'member').length || 0
		},
		byDuesStatus: {
			current: members?.filter(m => m.dues_status === 'current').length || 0,
			due_soon: members?.filter(m => m.dues_status === 'due_soon').length || 0,
			overdue: members?.filter(m => m.dues_status === 'overdue').length || 0,
			never_paid: members?.filter(m => m.dues_status === 'never_paid').length || 0
		}
	};

	// Group by status
	for (const member of members || []) {
		const status = member.status_display_name || 'Unknown';
		membershipStats.byStatus[status] = (membershipStats.byStatus[status] || 0) + 1;
	}

	// Calculate dues collection statistics
	const duesStats = {
		totalCollected: payments?.reduce((sum, p) => sum + (p.amount || 0), 0) || 0,
		paymentCount: payments?.length || 0,
		byMonth: {} as Record<string, { amount: number; count: number }>,
		byMethod: {} as Record<string, { amount: number; count: number }>
	};

	// Group payments by month
	for (const payment of payments || []) {
		const month = new Date(payment.payment_date).toLocaleDateString('en-US', { month: 'short', year: 'numeric' });
		if (!duesStats.byMonth[month]) {
			duesStats.byMonth[month] = { amount: 0, count: 0 };
		}
		duesStats.byMonth[month].amount += payment.amount || 0;
		duesStats.byMonth[month].count++;

		const method = payment.payment_method || 'Unknown';
		if (!duesStats.byMethod[method]) {
			duesStats.byMethod[method] = { amount: 0, count: 0 };
		}
		duesStats.byMethod[method].amount += payment.amount || 0;
		duesStats.byMethod[method].count++;
	}

	// Calculate event attendance statistics
	const eventStats = {
		totalEvents: events?.length || 0,
		totalAttendees: events?.reduce((sum, e) => sum + (e.total_attendees || 0), 0) || 0,
		averageAttendance: events?.length
			? Math.round((events.reduce((sum, e) => sum + (e.total_attendees || 0), 0) / events.length))
			: 0,
		byType: {} as Record<string, { count: number; attendees: number }>
	};

	// Group events by type
	for (const event of events || []) {
		const type = event.event_type_name || 'General';
		if (!eventStats.byType[type]) {
			eventStats.byType[type] = { count: 0, attendees: 0 };
		}
		eventStats.byType[type].count++;
		eventStats.byType[type].attendees += event.total_attendees || 0;
	}

	// Available years for dropdown
	const currentYear = new Date().getFullYear();
	const availableYears = Array.from({ length: 5 }, (_, i) => currentYear - i);

	return {
		reportType,
		year,
		availableYears,
		members: members || [],
		payments: payments || [],
		events: events || [],
		rsvps: rsvps || [],
		membershipStats,
		duesStats,
		eventStats
	};
};

// CSV export is handled by the GET endpoint at /board/reports/export/[type]
