/**
 * Email Service
 * Handles email notifications
 */

const nodemailer = require("nodemailer");

// Create transporter
const createTransporter = () => {
  return nodemailer.createTransport({
    host: process.env.SMTP_HOST || "smtp.gmail.com",
    port: process.env.SMTP_PORT || 587,
    secure: false,
    auth: {
      user: process.env.SMTP_USER,
      pass: process.env.SMTP_PASS,
    },
  });
};

/**
 * Send email
 */
const sendEmail = async (options) => {
  try {
    const transporter = createTransporter();

    const mailOptions = {
      from: `"Aerix Global" <${process.env.SMTP_USER}>`,
      to: options.to,
      subject: options.subject,
      html: options.html,
      text: options.text,
    };

    const info = await transporter.sendMail(mailOptions);
    console.log("Email sent:", info.messageId);
    return { success: true, messageId: info.messageId };
  } catch (error) {
    console.error("Email error:", error);
    return { success: false, error: error.message };
  }
};

/**
 * Send task assignment notification
 */
const sendTaskAssignmentEmail = async (employee, task) => {
  const html = `
        <div style="font-family: 'Poppins', Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <div style="background: linear-gradient(135deg, #0A1F44, #00C2CB); padding: 20px; text-align: center;">
                <h1 style="color: white; margin: 0;">Aerix Global</h1>
            </div>
            <div style="padding: 30px; background: #f5f5f5;">
                <h2 style="color: #0A1F44;">New Task Assigned</h2>
                <p>Hello ${employee.first_name},</p>
                <p>You have been assigned a new task:</p>
                <div style="background: white; padding: 20px; border-radius: 8px; margin: 20px 0;">
                    <h3 style="color: #00C2CB; margin-top: 0;">${task.title}</h3>
                    <p><strong>Priority:</strong> ${task.priority}</p>
                    <p><strong>Due Date:</strong> ${task.due_date || "Not set"}</p>
                    <p><strong>Description:</strong> ${task.description || "No description"}</p>
                </div>
                <a href="${process.env.FRONTEND_URL}/tasks/${task.id}" 
                   style="display: inline-block; background: #00C2CB; color: white; padding: 12px 24px; 
                          text-decoration: none; border-radius: 5px;">
                    View Task
                </a>
            </div>
            <div style="background: #0A1F44; padding: 15px; text-align: center;">
                <p style="color: #999; margin: 0; font-size: 12px;">
                    © ${new Date().getFullYear()} Aerix Global. All rights reserved.
                </p>
            </div>
        </div>
    `;

  return sendEmail({
    to: employee.email,
    subject: `New Task Assigned: ${task.title}`,
    html,
  });
};

/**
 * Send task deadline reminder
 */
const sendDeadlineReminderEmail = async (employee, task, daysUntilDue) => {
  const urgencyColor =
    daysUntilDue <= 1 ? "#dc3545" : daysUntilDue <= 3 ? "#ffc107" : "#00C2CB";

  const html = `
        <div style="font-family: 'Poppins', Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <div style="background: linear-gradient(135deg, #0A1F44, #00C2CB); padding: 20px; text-align: center;">
                <h1 style="color: white; margin: 0;">Aerix Global</h1>
            </div>
            <div style="padding: 30px; background: #f5f5f5;">
                <h2 style="color: ${urgencyColor};">⏰ Task Deadline Reminder</h2>
                <p>Hello ${employee.first_name},</p>
                <p>This is a reminder that you have a task due ${daysUntilDue === 0 ? "today" : `in ${daysUntilDue} day(s)`}:</p>
                <div style="background: white; padding: 20px; border-radius: 8px; margin: 20px 0; border-left: 4px solid ${urgencyColor};">
                    <h3 style="color: #0A1F44; margin-top: 0;">${task.title}</h3>
                    <p><strong>Due Date:</strong> ${task.due_date}</p>
                    <p><strong>Priority:</strong> ${task.priority}</p>
                    <p><strong>Status:</strong> ${task.status}</p>
                </div>
                <a href="${process.env.FRONTEND_URL}/tasks/${task.id}" 
                   style="display: inline-block; background: #00C2CB; color: white; padding: 12px 24px; 
                          text-decoration: none; border-radius: 5px;">
                    View Task
                </a>
            </div>
            <div style="background: #0A1F44; padding: 15px; text-align: center;">
                <p style="color: #999; margin: 0; font-size: 12px;">
                    © ${new Date().getFullYear()} Aerix Global. All rights reserved.
                </p>
            </div>
        </div>
    `;

  return sendEmail({
    to: employee.email,
    subject: `Task Deadline Reminder: ${task.title}`,
    html,
  });
};

/**
 * Send password reset email
 */
const sendPasswordResetEmail = async (user, resetToken) => {
  const resetUrl = `${process.env.FRONTEND_URL}/reset-password?token=${resetToken}`;

  const html = `
        <div style="font-family: 'Poppins', Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <div style="background: linear-gradient(135deg, #0A1F44, #00C2CB); padding: 20px; text-align: center;">
                <h1 style="color: white; margin: 0;">Aerix Global</h1>
            </div>
            <div style="padding: 30px; background: #f5f5f5;">
                <h2 style="color: #0A1F44;">Password Reset Request</h2>
                <p>Hello,</p>
                <p>We received a request to reset your password. Click the button below to create a new password:</p>
                <div style="text-align: center; margin: 30px 0;">
                    <a href="${resetUrl}" 
                       style="display: inline-block; background: #00C2CB; color: white; padding: 15px 30px; 
                              text-decoration: none; border-radius: 5px; font-weight: bold;">
                        Reset Password
                    </a>
                </div>
                <p style="color: #666; font-size: 14px;">
                    This link will expire in 1 hour. If you didn't request this, please ignore this email.
                </p>
            </div>
            <div style="background: #0A1F44; padding: 15px; text-align: center;">
                <p style="color: #999; margin: 0; font-size: 12px;">
                    © ${new Date().getFullYear()} Aerix Global. All rights reserved.
                </p>
            </div>
        </div>
    `;

  return sendEmail({
    to: user.email,
    subject: "Password Reset - Aerix Global",
    html,
  });
};

/**
 * Send welcome email to new employee
 */
const sendWelcomeEmail = async (employee, credentials) => {
  const html = `
        <div style="font-family: 'Poppins', Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <div style="background: linear-gradient(135deg, #0A1F44, #00C2CB); padding: 20px; text-align: center;">
                <h1 style="color: white; margin: 0;">Welcome to Aerix Global</h1>
            </div>
            <div style="padding: 30px; background: #f5f5f5;">
                <h2 style="color: #0A1F44;">Hello ${employee.first_name}! 👋</h2>
                <p>Welcome to the Aerix Global team! Your account has been created successfully.</p>
                <div style="background: white; padding: 20px; border-radius: 8px; margin: 20px 0;">
                    <h3 style="color: #00C2CB; margin-top: 0;">Your Login Credentials</h3>
                    <p><strong>Username:</strong> ${credentials.username}</p>
                    <p><strong>Temporary Password:</strong> ${credentials.password}</p>
                </div>
                <p style="color: #dc3545; font-weight: bold;">
                    ⚠️ Please change your password after first login.
                </p>
                <a href="${process.env.FRONTEND_URL}/login" 
                   style="display: inline-block; background: #00C2CB; color: white; padding: 12px 24px; 
                          text-decoration: none; border-radius: 5px;">
                    Login Now
                </a>
            </div>
            <div style="background: #0A1F44; padding: 15px; text-align: center;">
                <p style="color: #999; margin: 0; font-size: 12px;">
                    © ${new Date().getFullYear()} Aerix Global. All rights reserved.
                </p>
            </div>
        </div>
    `;

  return sendEmail({
    to: employee.email,
    subject: "Welcome to Aerix Global - Your Account Details",
    html,
  });
};

module.exports = {
  sendEmail,
  sendTaskAssignmentEmail,
  sendDeadlineReminderEmail,
  sendPasswordResetEmail,
  sendWelcomeEmail,
};
