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

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

	// Load all members with dues info using admin client (bypasses RLS for admin page)
	const { data: members } = await supabaseAdmin
		.from('members_with_dues')
		.select('*')
		.order('created_at', { ascending: false });

	// Filter members
	let filteredMembers = members || [];

	if (searchQuery) {
		const lowerSearch = searchQuery.toLowerCase();
		filteredMembers = filteredMembers.filter(
			(m: any) =>
				m.first_name?.toLowerCase().includes(lowerSearch) ||
				m.last_name?.toLowerCase().includes(lowerSearch) ||
				m.email?.toLowerCase().includes(lowerSearch) ||
				m.member_id?.toLowerCase().includes(lowerSearch)
		);
	}

	if (roleFilter !== 'all') {
		filteredMembers = filteredMembers.filter((m: any) => m.role === roleFilter);
	}

	if (statusFilter !== 'all') {
		filteredMembers = filteredMembers.filter((m: any) => m.status_name === statusFilter);
	}

	// Load membership statuses for dropdown
	const { data: statuses } = await supabaseAdmin
		.from('membership_statuses')
		.select('*')
		.order('sort_order', { ascending: true });

	// Calculate stats
	const stats = {
		total: members?.length || 0,
		admins: members?.filter((m: any) => m.role === 'admin').length || 0,
		board: members?.filter((m: any) => m.role === 'board').length || 0,
		members: members?.filter((m: any) => m.role === 'member').length || 0
	};

	return {
		members: filteredMembers,
		statuses: statuses || [],
		stats,
		filters: {
			search: searchQuery,
			role: roleFilter,
			status: statusFilter
		}
	};
};

export const actions: Actions = {
	updateRole: async ({ request, locals }) => {
		const { session } = await locals.safeGetSession();
		const formData = await request.formData();
		const memberId = formData.get('member_id') as string;
		const newRole = formData.get('role') as string;

		if (!memberId || !newRole) {
			return fail(400, { error: 'Member ID and role are required' });
		}

		if (!['member', 'board', 'admin'].includes(newRole)) {
			return fail(400, { error: 'Invalid role' });
		}

		// Prevent admin from changing their own role (belt-and-suspenders with RLS)
		if (session?.user && memberId === session.user.id) {
			return fail(403, { error: 'Cannot change your own role' });
		}

		const { error } = await locals.supabase
			.from('members')
			.update({ role: newRole, updated_at: new Date().toISOString() })
			.eq('id', memberId);

		if (error) {
			console.error('Update role error:', error);
			return fail(500, { error: 'Failed to update role' });
		}

		if (session?.user) {
			logMemberAction('role_change',
				{ id: session.user.id, email: session.user.email! },
				{ id: memberId },
				{ new_role: newRole }
			);
		}

		return { success: 'Role updated successfully!' };
	},

	updateStatus: async ({ request, locals }) => {
		const { session } = await locals.safeGetSession();
		const formData = await request.formData();
		const memberId = formData.get('member_id') as string;
		const statusId = formData.get('status_id') as string;

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

		const { error } = await locals.supabase
			.from('members')
			.update({
				membership_status_id: statusId,
				updated_at: new Date().toISOString()
			})
			.eq('id', memberId);

		if (error) {
			console.error('Update status error:', error);
			return fail(500, { error: 'Failed to update status' });
		}

		if (session?.user) {
			logMemberAction('status_change',
				{ id: session.user.id, email: session.user.email! },
				{ id: memberId },
				{ new_status_id: statusId }
			);
		}

		return { success: 'Status updated successfully!' };
	},

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

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

		const formData = await request.formData();
		const memberId = formData.get('member_id') as string;

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

		// Prevent admin from deleting themselves
		if (memberId === member.id) {
			return fail(400, { error: 'You cannot delete your own account' });
		}

		// First handle related records that have foreign keys to members

		// Reassign events created by this member to the current admin
		await supabaseAdmin
			.from('events')
			.update({ created_by: member.id })
			.eq('created_by', memberId);

		// Reassign app_settings updated by this member to the current admin
		await supabaseAdmin
			.from('app_settings')
			.update({ updated_by: member.id })
			.eq('updated_by', memberId);

		// Delete dues payments
		await supabaseAdmin.from('dues_payments').delete().eq('member_id', memberId);

		// Delete event RSVPs
		await supabaseAdmin.from('event_rsvps').delete().eq('member_id', memberId);

		// Delete email logs
		await supabaseAdmin.from('email_logs').delete().eq('recipient_id', memberId);
		await supabaseAdmin.from('email_logs').delete().eq('sent_by', memberId);

		// Now delete from members table using admin client (bypasses RLS)
		const { error } = await supabaseAdmin.from('members').delete().eq('id', memberId);

		if (error) {
			console.error('Delete member error:', error);
			console.error('Error details:', JSON.stringify(error, null, 2));
			return fail(500, { error: `Failed to delete member: ${error.message}` });
		}

		// Also delete the auth user using admin client
		const { error: authError } = await supabaseAdmin.auth.admin.deleteUser(memberId);

		if (authError) {
			console.error('Delete auth user error:', authError);
			// Member is already deleted, just log this
		}

		logMemberAction('delete',
			{ id: member.id, email: member.email! },
			{ id: memberId },
			{ deleted_by_admin: true }
		);

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

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

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

		const formData = await request.formData();
		const email = (formData.get('email') as string)?.trim().toLowerCase();
		const firstName = (formData.get('first_name') as string)?.trim() || '';
		const lastName = (formData.get('last_name') as string)?.trim() || '';
		const role = (formData.get('role') as string) || 'member';
		const duesPaidDate = formData.get('dues_paid_date') as string;

		if (!email) {
			return fail(400, { error: 'Email is required' });
		}

		// Validate role
		if (!['member', 'board', 'admin'].includes(role)) {
			return fail(400, { error: 'Invalid role' });
		}

		// Validate email format
		const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
		if (!emailRegex.test(email)) {
			return fail(400, { error: 'Please enter a valid email address' });
		}

		// Check if email already exists
		const { data: existingMember } = await locals.supabase
			.from('members')
			.select('id')
			.eq('email', email)
			.single();

		if (existingMember) {
			return fail(400, { error: 'A member with this email already exists' });
		}

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

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

		// Create auth user with a temporary password using admin client (requires service_role)
		// The user will reset their password when they first log in
		const tempPassword = crypto.randomUUID();

		const { data: authData, error: authError } = await supabaseAdmin.auth.admin.createUser({
			email,
			password: tempPassword,
			email_confirm: true, // Auto-confirm the email since admin is inviting
			user_metadata: {
				first_name: firstName || 'New',
				last_name: lastName || 'Member',
				invited_by: member.id
			}
		});

		if (authError) {
			console.error('Auth user creation error:', authError);
			if (authError.message.includes('already registered')) {
				return fail(400, { error: 'This email is already registered' });
			}
			return fail(500, { error: 'Failed to create user account. Please try again.' });
		}

		if (!authData.user) {
			return fail(500, { error: 'Failed to create user account' });
		}

		// Get active status if dues are paid
		let statusId = defaultStatus?.id;
		if (duesPaidDate) {
			const { data: activeStatus } = await locals.supabase
				.from('membership_statuses')
				.select('id')
				.eq('name', 'active')
				.single();
			if (activeStatus) {
				statusId = activeStatus.id;
			}
		}

		// Create member record
		const { error: memberError } = await locals.supabase.from('members').insert({
			id: authData.user.id,
			first_name: firstName || 'New',
			last_name: lastName || 'Member',
			email: email,
			phone: '',
			date_of_birth: '1990-01-01', // Placeholder - member will update
			address: 'TBD', // Placeholder
			nationality: [],
			role: role,
			membership_status_id: statusId,
			membership_type_id: defaultType?.id
		});

		if (memberError) {
			console.error('Member creation error:', memberError);
			// Clean up auth user using admin client
			await supabaseAdmin.auth.admin.deleteUser(authData.user.id);
			return fail(500, { error: 'Failed to create member record. Please try again.' });
		}

		// Create dues payment record if dues paid date is provided
		// The dues_paid_date is the date when dues are NEXT due (not when paid)
		// So we calculate payment_date as 1 year before the due date
		if (duesPaidDate) {
			const dueDate = new Date(duesPaidDate);
			const paymentDate = new Date(dueDate);
			paymentDate.setFullYear(paymentDate.getFullYear() - 1);

			const { error: duesError } = await locals.supabase.from('dues_payments').insert({
				member_id: authData.user.id,
				amount: defaultType?.annual_dues || 0,
				payment_date: paymentDate.toISOString().split('T')[0],
				due_date: duesPaidDate,
				payment_method: 'other',
				notes: 'Initial dues set by admin during member invitation',
				recorded_by: member.id
			});

			if (duesError) {
				console.error('Dues payment creation error:', duesError);
				// Non-critical - member still created
			}
		}

		// Send welcome email with Monaco branding
		const baseUrl = url.origin;
		const logoUrl = `${baseUrl}/MONACOUSA-Flags_376x376.png`;
		const memberFirstName = firstName || 'New Member';

		// Format dues paid date for display
		const formattedDuesPaidDate = duesPaidDate
			? new Date(duesPaidDate).toLocaleDateString('en-US', {
					year: 'numeric',
					month: 'long',
					day: 'numeric'
				})
			: null;

		// Dues section for the email
		const duesSection = duesPaidDate
			? `<div style="background: #f0fdf4; border: 1px solid #bbf7d0; border-radius: 12px; padding: 20px; margin: 0 0 20px 0;">
                <p style="margin: 0 0 8px 0; color: #166534; font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px;">Membership Status</p>
                <p style="margin: 0 0 8px 0; color: #334155;"><strong>Status:</strong> Active Member</p>
                <p style="margin: 0; color: #334155;"><strong>Dues Paid Through:</strong> ${formattedDuesPaidDate}</p>
              </div>`
			: '';

		const welcomeEmailResult = await sendEmail({
			to: email,
			subject: `Welcome to Monaco USA, ${memberFirstName}!`,
			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;">Welcome to Monaco USA!</h2>
              <p style="margin: 0 0 16px 0; color: #334155; line-height: 1.6;">Dear ${memberFirstName},</p>
              <p style="margin: 0 0 16px 0; color: #334155; line-height: 1.6;">We are thrilled to welcome you to the Monaco USA community! Your membership account has been created and you are now part of our growing network of Americans in Monaco.</p>
              ${duesSection}
              <div style="background: #f8fafc; border-radius: 12px; padding: 20px; margin: 0 0 20px 0;">
                <p style="margin: 0 0 12px 0; color: #334155; font-weight: 600;">To get started:</p>
                <ol style="margin: 0; padding: 0 0 0 20px; color: #334155; line-height: 1.8;">
                  <li>You will receive a separate email shortly to set up your password</li>
                  <li>Log in to your member portal at <a href="${baseUrl}" style="color: #CE1126; text-decoration: none;">${baseUrl}</a></li>
                  <li>Complete your profile with your details</li>
                  <li>Explore upcoming events and connect with fellow members</li>
                </ol>
              </div>
              <p style="margin: 0 0 20px 0; color: #334155; line-height: 1.6;">If you have any questions, please don't hesitate to reach out to our board members.</p>
              <p style="margin: 0; color: #334155;">Best regards,<br><strong style="color: #CE1126;">The Monaco USA Team</strong></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: authData.user.id,
			recipientName: `${firstName} ${lastName}`.trim() || 'New Member',
			emailType: 'welcome',
			sentBy: member.id
		});

		if (!welcomeEmailResult.success) {
			console.error('Welcome email error:', welcomeEmailResult.error);
			// Non-critical - member still created
		}

		// Send password reset email so user can set their own password
		const { error: resetError } = await locals.supabase.auth.resetPasswordForEmail(email, {
			redirectTo: `${url.origin}/auth/reset-password`
		});

		if (resetError) {
			console.error('Password reset email error:', resetError);
			// Member created but email failed - not critical
		}

		return {
			success: `Invitation sent to ${email}! They will receive a welcome email and instructions to set up their password.`
		};
	}
};
