import nodemailer from "nodemailer";
import logger from "../utils/logger.js";

// Email Configuration
let transporter = null;
if (process.env.SMTP_HOST && process.env.SMTP_USER && process.env.SMTP_PASS) {
  try {
    transporter = nodemailer.createTransport({
      host: process.env.SMTP_HOST,
      port: parseInt(process.env.SMTP_PORT || "465"),
      secure: process.env.SMTP_PORT === "465" || process.env.SMTP_SECURE === "true",
      auth: {
        user: process.env.SMTP_USER,
        pass: process.env.SMTP_PASS,
      },
    });
    logger.info("Email transporter configured successfully for interviews");
  } catch (err) {
    logger.error("Failed to create email transporter:", err.message);
  }
} else {
  logger.warn("Email transporter not configured - missing SMTP credentials");
}

/**
 * Send interview confirmation emails to candidate and admin
 * @param {Object} interviewData - Interview details
 * @param {string} interviewData.candidateName - Candidate's full name
 * @param {string} interviewData.candidateEmail - Candidate's email
 * @param {string} interviewData.role - Job role/position
 * @param {Date|string} interviewData.interviewDate - Interview date and time
 * @param {string} interviewData.interviewType - "Remote" or "Onsite"
 * @param {string} interviewData.interviewer - Interviewer's name
 * @param {string} [interviewData.meetingUrl] - Meeting URL (for remote interviews)
 * @param {string} [interviewData.location] - Location (for onsite interviews)
 * @param {string} [interviewData.notes] - Additional notes
 */
export async function sendInterviewEmails(interviewData) {
  const {
    candidateName,
    candidateEmail,
    role,
    interviewDate,
    interviewType,
    interviewer,
    meetingUrl,
    location,
    notes,
  } = interviewData;

  if (!transporter) {
    logger.warn("Email transporter not configured. Skipping interview email notifications.");
    throw new Error("Email service is not configured. Please set SMTP_HOST, SMTP_USER, and SMTP_PASS in Backend/.env");
  }

  const adminEmail = process.env.ADMIN_EMAIL;
  const companyEmail = process.env.COMPANY_EMAIL || adminEmail || process.env.SMTP_USER;

  // Format interview date
  const interviewDateTime = new Date(interviewDate);
  const formattedDate = interviewDateTime.toLocaleString("en-PK", {
    timeZone: "Asia/Karachi",
    hour12: true,
    year: "numeric",
    month: "long",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });

  // Admin Email HTML
  const adminEmailHTML = `
<div style="font-family: system-ui, sans-serif, Arial; font-size: 15px; color: #333; padding: 14px 8px; background-color: #f5f5f5;">
  <div style="max-width: 600px; margin: auto; background-color: #fff; border-radius: 8px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); overflow: hidden;">
    <div style="border-top: 6px solid #6366f1; padding: 16px;">
      <span style="font-size: 18px; font-weight: 600; color: #6366f1;">New Interview Scheduled</span>
    </div>
    <div style="padding: 24px 16px;">
      <p><strong>Candidate Name:</strong> ${candidateName || "N/A"}</p>
      <p><strong>Candidate Email:</strong> ${candidateEmail || "N/A"}</p>
      <div style="margin: 14px 0;">
        <p style="margin: 0 0 6px 0;"><strong>Position:</strong> ${role || "N/A"}</p>
        <p style="margin: 0 0 6px 0;"><strong>Interview Type:</strong> ${interviewType || "N/A"}</p>
        <p style="margin: 0 0 6px 0;"><strong>Interviewer:</strong> ${interviewer || "N/A"}</p>
        <p style="margin: 0 0 6px 0;"><strong>Interview Date & Time:</strong> ${formattedDate}</p>
        ${interviewType === "Remote" && meetingUrl ? `<p style="margin: 0 0 6px 0;"><strong>Meeting Link:</strong> <a href="${meetingUrl}" style="color: #6366f1;">${meetingUrl}</a></p>` : ""}
        ${interviewType === "Onsite" && location ? `<p style="margin: 0 0 6px 0;"><strong>Location:</strong> ${location}</p>` : ""}
        ${notes ? `<p style="margin: 10px 0 6px 0;"><strong>Notes:</strong></p>
        <div style="white-space: pre-wrap; border: 1px solid #eee; background: #fafafa; padding: 10px; border-radius: 6px;">${notes}</div>` : ""}
      </div>
    </div>
  </div>
</div>`;

  // Send admin email
  if (adminEmail) {
    try {
      await transporter.sendMail({
        from: `"Interview Scheduler" <${process.env.SMTP_USER}>`,
        to: adminEmail,
        replyTo: candidateEmail,
        subject: `New Interview Scheduled: ${candidateName} - ${role}`,
        html: adminEmailHTML,
      });
      logger.info(`Admin interview notification email sent successfully to: ${adminEmail}`);
    } catch (err) {
      logger.error("Failed to send admin interview email:", err.message);
      throw err;
    }
  }

  // Candidate Confirmation Email HTML
  const candidateEmailHTML = `
<div style="font-family: system-ui, sans-serif, Arial; font-size: 15px; color: #333; padding: 14px 8px; background-color: #f5f5f5;">
  <div style="max-width: 600px; margin: auto; background-color: #fff; border-radius: 8px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); overflow: hidden;">
    <div style="border-top: 6px solid #6366f1; padding: 16px;">
      <span style="font-size: 18px; font-weight: 600; color: #6366f1;">Interview Confirmation</span>
    </div>
    <div style="padding: 24px 16px;">
      <p>Hi ${candidateName || "there"},</p>
      <p>Your interview has been successfully scheduled! Here are the details:</p>
      <div style="background-color: #f0f0ff; border: 1px solid #d6d6ff; border-radius: 6px; padding: 16px; margin: 20px 0;">
        <p style="margin: 0 0 8px 0;"><strong>📋 Position:</strong> ${role || "N/A"}</p>
        <p style="margin: 0 0 8px 0;"><strong>🕒 Interview Date & Time:</strong> ${formattedDate}</p>
        <p style="margin: 0 0 8px 0;"><strong>👤 Interviewer:</strong> ${interviewer || "TBD"}</p>
        <p style="margin: 0 0 8px 0;"><strong>📍 Interview Type:</strong> ${interviewType || "N/A"}</p>
        ${interviewType === "Remote" && meetingUrl ? `
        <p style="margin: 8px 0 0 0;"><strong>💻 Meeting Link:</strong><br/>
        <a href="${meetingUrl}" style="color: #6366f1; word-break: break-all;">${meetingUrl}</a></p>
        ` : ""}
        ${interviewType === "Onsite" && location ? `
        <p style="margin: 8px 0 0 0;"><strong>📍 Location:</strong> ${location}</p>
        ` : ""}
        ${notes ? `<p style="margin: 8px 0 0 0;"><strong>📝 Additional Notes:</strong><br/>${notes}</p>` : ""}
      </div>
      ${interviewType === "Remote" && meetingUrl ? `
      <div style="text-align: center; margin: 24px 0;">
        <a href="${meetingUrl}" style="background-color: #6366f1; color: #fff; text-decoration: none; padding: 12px 24px; border-radius: 6px; display: inline-block; font-weight: 600; font-size: 16px;">Join Interview</a>
      </div>
      ` : ""}
      <p style="margin-top: 24px;">
        We look forward to speaking with you!<br />
        <strong>${companyEmail ? companyEmail.split("@")[0] : "HR"} Team</strong><br />
        <span style="color: #888;">${companyEmail}</span>
      </p>
    </div>
  </div>
</div>`;

  // Send candidate email
  if (candidateEmail) {
    try {
      await transporter.sendMail({
        from: `"Interview Scheduler" <${process.env.SMTP_USER}>`,
        to: candidateEmail,
        replyTo: companyEmail,
        subject: `Interview Confirmation - ${role} at ${companyEmail ? companyEmail.split("@")[0] : "Our Company"}`,
        html: candidateEmailHTML,
      });
      logger.info(`Candidate interview confirmation email sent successfully to: ${candidateEmail}`);
    } catch (err) {
      logger.error("Failed to send candidate interview email:", err.message);
      throw err;
    }
  } else {
    logger.warn("No candidate email provided, skipping candidate confirmation email");
  }
}

