import { MailService } from '@sendgrid/mail';

if (!process.env.SENDGRID_API_KEY) {
  console.warn("SENDGRID_API_KEY environment variable not set. Email functionality will be disabled.");
}

const mailService = new MailService();
if (process.env.SENDGRID_API_KEY) {
  mailService.setApiKey(process.env.SENDGRID_API_KEY);
}

interface WelcomeEmailParams {
  to: string;
  firstName: string;
  lastName: string;
  username: string;
  password: string;
  organizationName?: string;
}

interface ConfirmationEmailParams {
  to: string;
  firstName: string;
  verificationToken: string;
  baseUrl: string;
}

interface SendEmailParams {
  to: string;
  subject: string;
  html: string;
  text?: string;
}

export async function sendWelcomeEmail(params: WelcomeEmailParams): Promise<boolean> {
  if (!process.env.SENDGRID_API_KEY) {
    console.log("Email would be sent to:", params.to);
    console.log("Login credentials - Username:", params.username, "Password:", params.password);
    return false;
  }

  try {
    const htmlContent = `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Welcome to Sports Management Platform</title>
        <style>
          body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
          .container { max-width: 600px; margin: 0 auto; padding: 20px; }
          .header { background: #1976D2; color: white; padding: 20px; text-align: center; }
          .content { padding: 30px; background: #f9f9f9; }
          .credentials { background: white; padding: 20px; border-radius: 8px; margin: 20px 0; }
          .footer { text-align: center; padding: 20px; color: #666; font-size: 14px; }
          .button { background: #1976D2; color: white; padding: 12px 24px; text-decoration: none; border-radius: 4px; display: inline-block; }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">
            <h1>Welcome to Sports Management Platform</h1>
          </div>
          <div class="content">
            <h2>Hello ${params.firstName} ${params.lastName},</h2>
            <p>Your account has been created for the Sports Management Platform${params.organizationName ? ` at ${params.organizationName}` : ''}.</p>
            
            <div class="credentials">
              <h3>Your Login Credentials:</h3>
              <p><strong>Username:</strong> ${params.username}</p>
              <p><strong>Password:</strong> ${params.password}</p>
            </div>
            
            <p>For security reasons, we recommend changing your password after your first login.</p>
            <p>You can access the platform using the link below:</p>
            <p style="text-align: center;">
              <a href="${process.env.BASE_URL || 'https://your-app.replit.app'}" class="button">Login to Platform</a>
            </p>
          </div>
          <div class="footer">
            <p>This is an automated message. Please do not reply to this email.</p>
            <p>If you have any questions, please contact your system administrator.</p>
          </div>
        </div>
      </body>
      </html>
    `;

    const textContent = `
      Welcome to Sports Management Platform

      Hello ${params.firstName} ${params.lastName},

      Your account has been created for the Sports Management Platform${params.organizationName ? ` at ${params.organizationName}` : ''}.

      Your Login Credentials:
      Username: ${params.username}
      Password: ${params.password}

      For security reasons, we recommend changing your password after your first login.

      You can access the platform at: ${process.env.BASE_URL || 'https://your-app.replit.app'}

      This is an automated message. Please do not reply to this email.
      If you have any questions, please contact your system administrator.
    `;

    await mailService.send({
      to: params.to,
      from: process.env.FROM_EMAIL || 'noreply@sportsmanagement.com',
      subject: 'Welcome to Sports Management Platform - Your Account Details',
      text: textContent,
      html: htmlContent,
    });

    return true;
  } catch (error) {
    console.error('SendGrid email error:', error);
    return false;
  }
}

export async function sendEmail(params: SendEmailParams): Promise<boolean> {
  if (!process.env.SENDGRID_API_KEY) {
    console.log("Email would be sent to:", params.to);
    console.log("Subject:", params.subject);
    return false;
  }

  try {
    await mailService.send({
      to: params.to,
      from: process.env.FROM_EMAIL || 'noreply@sportsmanagement.com',
      subject: params.subject,
      html: params.html,
      text: params.text,
    });

    return true;
  } catch (error) {
    console.error('SendGrid email error:', error);
    return false;
  }
}

export async function sendPasswordResetEmail(to: string, firstName: string, newPassword: string): Promise<boolean> {
  if (!process.env.SENDGRID_API_KEY) {
    console.log("Password reset email would be sent to:", to);
    console.log("New password:", newPassword);
    return false;
  }

  try {
    const htmlContent = `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Password Reset - Sports Management Platform</title>
        <style>
          body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
          .container { max-width: 600px; margin: 0 auto; padding: 20px; }
          .header { background: #1976D2; color: white; padding: 20px; text-align: center; }
          .content { padding: 30px; background: #f9f9f9; }
          .credentials { background: white; padding: 20px; border-radius: 8px; margin: 20px 0; }
          .footer { text-align: center; padding: 20px; color: #666; font-size: 14px; }
          .button { background: #1976D2; color: white; padding: 12px 24px; text-decoration: none; border-radius: 4px; display: inline-block; }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">
            <h1>Password Reset</h1>
          </div>
          <div class="content">
            <h2>Hello ${firstName},</h2>
            <p>Your password has been reset by an administrator.</p>
            
            <div class="credentials">
              <h3>Your New Password:</h3>
              <p><strong>Password:</strong> ${newPassword}</p>
            </div>
            
            <p><strong>Important:</strong> For security reasons, please change this password immediately after logging in.</p>
            <p style="text-align: center;">
              <a href="${process.env.BASE_URL || 'https://your-app.replit.app'}" class="button">Login to Platform</a>
            </p>
          </div>
          <div class="footer">
            <p>This is an automated message. Please do not reply to this email.</p>
            <p>If you did not request this password reset, please contact your system administrator immediately.</p>
          </div>
        </div>
      </body>
      </html>
    `;

    await mailService.send({
      to,
      from: process.env.FROM_EMAIL || 'noreply@sportsmanagement.com',
      subject: 'Password Reset - Sports Management Platform',
      html: htmlContent,
    });

    return true;
  } catch (error) {
    console.error('SendGrid email error:', error);
    return false;
  }
}