import nodemailer from "nodemailer"
import fs from "fs";
import path from "path";

// Create transporter (reusable)
const createTransporter = () => {
  return nodemailer.createTransport({
    host: "mail.cssawwwards.com",
    port: 465,
    secure: true,
    auth: {
      user: process.env.CPANEL_EMAIL || "contact@cssawwwards.com",
      pass: process.env.CPANEL_EMAIL_PASSWORD,
    },
    tls: {
      rejectUnauthorized: false // Bypass SSL certificate validation if needed
    },
    debug: true, // Enable debugging
    logger: true // Log output
  });
};

export const sendWelcomeEmail = async (toEmail, userName) => {
    try {
        const templatePath = path.resolve("./templates/welcomeEmail.html");
        let htmlTemplate = fs.readFileSync(templatePath, "utf8");

        // Replace placeholder
        htmlTemplate = htmlTemplate.replace("{{firstName}}", userName || "there");

        // Create plain text version
        const plainText = `
Welcome to CSSAwwwards, ${userName || "there"}!

Thank you for registering with CSSAwwwards. We're excited to have you join our global community of designers, developers, and creative professionals.

What You Can Do:
- Submit your websites for recognition and awards
- Vote and provide feedback on innovative designs
- Discover the best web design inspiration
- Connect with other professionals
- Build your portfolio and gain credibility

Get Started: https://cssawwwards.com/dashboard

If you have any questions, feel free to reach out to our support team.

Welcome aboard!

Best regards,
The CSSAwwwards Team

Recognition, Credibility, Global Exposure
For agencies, freelancers and all design community.
Copyright © 2025 CSSAwwwards. All rights reserved.
        `.trim();

        const transporter = createTransporter();

        await transporter.sendMail({
            from: '"CSSAwwwards" <noreply@cssawwwards.com>',
            replyTo: '"CSSAwwwards Support" <noreply@cssawwwards.com>',
            to: toEmail,
            subject: 'Welcome to CSSAwwwards - Registration Completed',
            text: plainText,
            html: htmlTemplate,
            headers: {
                'X-Mailer': 'CSSAwwwards Notification System',
                'Organization': 'CSSAwwwards',
                'List-Unsubscribe': '<https://cssawwwards.com/unsubscribe>',
            },
            priority: 'normal',
        });
        console.log("✅ Welcome email sent to:", toEmail);
    } catch (err) {
        console.error("❌ Welcome email error:", err);
    }
};

export const sendVerificationEmail = async (toEmail, userName, verificationToken) => {
    try {
        const templatePath = path.resolve("./templates/verificationEmail.html");
        let htmlTemplate = fs.readFileSync(templatePath, "utf8");

        // Create verification link
        const verificationLink = `${process.env.FRONTEND_URL || 'https://cssawwwards.com'}/verify-email/${verificationToken}`;

        // Replace placeholders
        htmlTemplate = htmlTemplate
            .replace(/{{userName}}/g, userName || "there")
            .replace(/{{verificationLink}}/g, verificationLink);

        // Create plain text version
        const plainText = `
Hi ${userName || "there"},

Thank you for signing up to CSSAwwwards!

To complete your registration and start using your account, please verify your email address by clicking the link below:

${verificationLink}

⏰ Important: This verification link will expire in 24 hours.

If you didn't create an account, you can safely ignore this email.

After verification, you'll be able to:
- Submit your websites for awards and recognition
- Vote and provide feedback on designs
- Build your portfolio and gain credibility
- Connect with a global design community

Need help? Contact us at support@cssawwwards.com

Best regards,
The CSSAwwwards Team

Recognition, Credibility, Global Exposure
For agencies, freelancers and all design community.
Copyright © 2025 CSSAwwwards. All rights reserved.
        `.trim();

        const transporter = createTransporter();

        await transporter.sendMail({
            from:  '"CSSAwwwards" <noreply@cssawwwards.com>',
            replyTo: '"CSSAwwwards Support" <noreply@cssawwwards.com>',
            to: toEmail,
            subject: 'Verify Your Email - CSSAwwwards',
            text: plainText,
            html: htmlTemplate,
            headers: {
                'X-Mailer': 'CSSAwwwards Notification System',
                'Organization': 'CSSAwwwards',
            },
            priority: 'high',
        });
        console.log("✅ Verification email sent to:", toEmail);
    } catch (err) {
        console.error("❌ Verification email error:", err);
        throw err; // Re-throw to handle in calling function
    }
};

export const sendWebsiteSubmissionEmail = async (toEmail, submissionData) => {
    try {
        console.log("📧 Preparing website submission email for:", toEmail);
        const templatePath = path.resolve("./templates/websiteSubmissionEmail.html");
        let htmlTemplate = fs.readFileSync(templatePath, "utf8");

        // Format date
        const submissionDate = new Date(submissionData.submissionDate).toLocaleDateString('en-US', {
            year: 'numeric',
            month: 'long',
            day: 'numeric'
        });

        // Replace placeholders
        htmlTemplate = htmlTemplate
            .replace("{{userName}}", submissionData.userName || "there")
            .replace(/{{websiteTitle}}/g, submissionData.websiteTitle || "Your Website")
            .replace(/{{websiteUrl}}/g, submissionData.websiteUrl || "#")
            .replace("{{category}}", submissionData.category || "N/A")
            .replace("{{submissionDate}}", submissionDate)
            .replace("{{paymentOrderID}}", submissionData.paymentOrderID || "N/A")
            .replace("{{paymentAmount}}", submissionData.paymentAmount || "0.00")
            .replace("{{paymentCurrency}}", submissionData.paymentCurrency || "USD");

        // Create plain text version
        const plainText = `
Hi ${submissionData.userName || "there"},

Great news! Your website "${submissionData.websiteTitle}" has been successfully submitted to CSSAwwwards for review.

Submission Details:
- Website: ${submissionData.websiteTitle}
- URL: ${submissionData.websiteUrl}
- Category: ${submissionData.category || "N/A"}
- Submission Date: ${submissionDate}

Payment Confirmed:
- Order ID: ${submissionData.paymentOrderID || "N/A"}
- Amount: ${submissionData.paymentAmount || "0.00"} ${submissionData.paymentCurrency || "USD"}
- Status: Verified

What happens next?
1. Our team will review your submission within 2-3 business days
2. Your website will be evaluated for design, usability, creativity, and content
3. Once approved, it will be published and visible to our global community
4. You'll receive voting and feedback from designers worldwide

View Your Submissions: https://cssawwwards.com/dashboard

Thank you for choosing CSSAwwwards!

Best regards,
The CSSAwwwards Team

Recognition, Credibility, Global Exposure
For agencies, freelancers and all design community.
Copyright © 2025 CSSAwwwards. All rights reserved.
        `.trim();

        const transporter = createTransporter();

        console.log("📤 Sending email via SMTP...");
        const info = await transporter.sendMail({
            from: '"CSSAwwwards" <noreply@cssawwwards.com>',
            replyTo: '"CSSAwwwards Support" <noreply@cssawwwards.com>',
            to: toEmail,
            subject: `Website "${submissionData.websiteTitle}" Successfully Submitted - CSSAwwwards`,
            text: plainText,
            html: htmlTemplate,
            headers: {
                'X-Entity-Ref-ID': submissionData.paymentOrderID || 'submission',
                'X-Mailer': 'CSSAwwwards Notification System',
                'Organization': 'CSSAwwwards',
                'List-Unsubscribe': '<https://cssawwwards.com/unsubscribe>',
            },
            priority: 'normal',
        });
        console.log("✅ Website submission email sent successfully!");
        console.log("📧 Message ID:", info.messageId);
    } catch (err) {
        console.error("❌ Website submission email error:");
        console.error("Error code:", err.code);
        console.error("Error message:", err.message);
        console.error("Full error:", err);
        throw err; // Re-throw to let caller know it failed
    }
};

export const sendAIWebsiteSubmissionEmail = async (toEmail, submissionData) => {
    try {
        const templatePath = path.resolve("./templates/aiWebsiteSubmissionEmail.html");
        let htmlTemplate = fs.readFileSync(templatePath, "utf8");

        // Format date
        const submissionDate = new Date(submissionData.submissionDate).toLocaleDateString('en-US', {
            year: 'numeric',
            month: 'long',
            day: 'numeric'
        });

        // Format arrays
        const category = Array.isArray(submissionData.category) 
            ? submissionData.category.join(', ') 
            : submissionData.category || 'N/A';
        
        const pricingOption = Array.isArray(submissionData.pricingOption)
            ? submissionData.pricingOption.join(', ')
            : submissionData.pricingOption || 'N/A';

        // Replace placeholders
        htmlTemplate = htmlTemplate
            .replace("{{userName}}", submissionData.userName || "there")
            .replace(/{{websiteTitle}}/g, submissionData.websiteTitle || "Your AI Website")
            .replace(/{{websiteUrl}}/g, submissionData.websiteUrl || "#")
            .replace("{{category}}", category)
            .replace("{{pricingOption}}", pricingOption)
            .replace("{{submissionDate}}", submissionDate)
            .replace("{{paymentOrderID}}", submissionData.paymentOrderID || "N/A")
            .replace("{{paymentAmount}}", submissionData.paymentAmount || "0.00")
            .replace("{{paymentCurrency}}", submissionData.paymentCurrency || "USD");

        // Create plain text version
        const plainText = `
Hi ${submissionData.userName || "there"},

Great news! Your AI website "${submissionData.websiteTitle}" has been successfully submitted to CSSAwwwards for review.

Submission Details:
- AI Website: ${submissionData.websiteTitle}
- URL: ${submissionData.websiteUrl}
- Category: ${category}
- Pricing: ${pricingOption}
- Submission Date: ${submissionDate}

Payment Confirmed:
- Order ID: ${submissionData.paymentOrderID || "N/A"}
- Amount: ${submissionData.paymentAmount || "0.00"} ${submissionData.paymentCurrency || "USD"}
- Status: Verified

What happens next?
1. Our team will review your submission within 2-3 business days
2. Your AI website will be evaluated and featured in our AI directory
3. Once approved, it will be published and visible to our global community
4. You'll gain exposure to designers and AI enthusiasts worldwide

View Your Submissions: https://cssawwwards.com/dashboard

Thank you for choosing CSSAwwwards!

Best regards,
The CSSAwwwards Team

Recognition, Credibility, Global Exposure
For agencies, freelancers and all design community.
Copyright © 2025 CSSAwwwards. All rights reserved.
        `.trim();

        const transporter = createTransporter();

        await transporter.sendMail({
            from: '"CSSAwwwards" <noreply@cssawwwards.com>',
            replyTo: '"CSSAwwwards Support" <noreply@cssawwwards.com>',
            to: toEmail,
            subject: `AI Website "${submissionData.websiteTitle}" Successfully Submitted - CSSAwwwards`,
            text: plainText,
            html: htmlTemplate,
            headers: {
                'X-Entity-Ref-ID': submissionData.paymentOrderID || 'ai-submission',
                'X-Mailer': 'CSSAwwwards Notification System',
                'Organization': 'CSSAwwwards',
                'List-Unsubscribe': '<https://cssawwwards.com/unsubscribe>',
            },
            priority: 'normal',
        });
        console.log("✅ AI website submission email sent to:", toEmail);
    } catch (err) {
        console.error("❌ AI website submission email error:", err);
    }
};

export const sendDirectorySubmissionEmail = async (toEmail, submissionData) => {
    try {
        const templatePath = path.resolve("./templates/directorySubmissionEmail.html");
        let htmlTemplate = fs.readFileSync(templatePath, "utf8");

        // Format date
        const submissionDate = new Date(submissionData.submissionDate).toLocaleDateString('en-US', {
            year: 'numeric',
            month: 'long',
            day: 'numeric'
        });

        // Replace placeholders
        htmlTemplate = htmlTemplate
            .replace("{{userName}}", submissionData.userName || "there")
            .replace(/{{companyTitle}}/g, submissionData.companyTitle || "Your Company")
            .replace(/{{websiteUrl}}/g, submissionData.websiteUrl || "#")
            .replace("{{profile}}", submissionData.profile || "N/A")
            .replace("{{country}}", submissionData.country || "N/A")
            .replace("{{submissionDate}}", submissionDate)
            .replace("{{paymentOrderID}}", submissionData.paymentOrderID || "N/A")
            .replace("{{paymentAmount}}", submissionData.paymentAmount || "0.00")
            .replace("{{paymentCurrency}}", submissionData.paymentCurrency || "USD");

        // Create plain text version
        const plainText = `
Hi ${submissionData.userName || "there"},

Great news! "${submissionData.companyTitle}" has been successfully added to the CSSAwwwards directory.

Submission Details:
- Company: ${submissionData.companyTitle}
- Website: ${submissionData.websiteUrl}
- Profile: ${submissionData.profile || "N/A"}
- Country: ${submissionData.country || "N/A"}
- Submission Date: ${submissionDate}

Payment Confirmed:
- Order ID: ${submissionData.paymentOrderID || "N/A"}
- Amount: ${submissionData.paymentAmount || "0.00"} ${submissionData.paymentCurrency || "USD"}
- Status: Verified

What happens next?
1. Our team will review your directory listing within 2-3 business days
2. Your company will be featured in our directory for increased visibility
3. Once approved, it will be published and visible to our global community
4. You'll gain exposure to potential clients and partners worldwide

View Your Submissions: https://cssawwwards.com/dashboard

Thank you for choosing CSSAwwwards!

Best regards,
The CSSAwwwards Team

Recognition, Credibility, Global Exposure
For agencies, freelancers and all design community.
Copyright © 2025 CSSAwwwards. All rights reserved.
        `.trim();

        const transporter = createTransporter();

        await transporter.sendMail({
            from: '"CSSAwwwards" <noreply@cssawwwards.com >',
            replyTo: '"CSSAwwwards Support" <noreply@cssawwwards.com>',
            to: toEmail,
            subject: `"${submissionData.companyTitle}" Successfully Added to Directory - CSSAwwwards`,
            text: plainText,
            html: htmlTemplate,
            headers: {
                'X-Entity-Ref-ID': submissionData.paymentOrderID || 'directory-submission',
                'X-Mailer': 'CSSAwwwards Notification System',
                'Organization': 'CSSAwwwards',
                'List-Unsubscribe': '<https://cssawwwards.com/unsubscribe>',
            },
            priority: 'normal',
        });
        console.log("✅ Directory submission email sent to:", toEmail);
    } catch (err) {
        console.error("❌ Directory submission email error:", err);
    }
};

export const sendJobSubmissionEmail = async (toEmail, submissionData) => {
    try {
        const templatePath = path.resolve("./templates/jobSubmissionEmail.html");
        let htmlTemplate = fs.readFileSync(templatePath, "utf8");

        // Format date
        const submissionDate = new Date(submissionData.submissionDate).toLocaleDateString('en-US', {
            year: 'numeric',
            month: 'long',
            day: 'numeric'
        });

        // Replace placeholders
        htmlTemplate = htmlTemplate
            .replace("{{userName}}", submissionData.userName || "there")
            .replace(/{{jobTitle}}/g, submissionData.jobTitle || "Your Job")
            .replace("{{companyName}}", submissionData.companyName || "N/A")
            .replace("{{jobType}}", submissionData.jobType || "N/A")
            .replace("{{category}}", submissionData.category || "N/A")
            .replace("{{submissionDate}}", submissionDate)
            .replace("{{paymentOrderID}}", submissionData.paymentOrderID || "N/A")
            .replace("{{paymentAmount}}", submissionData.paymentAmount || "0.00")
            .replace("{{paymentCurrency}}", submissionData.paymentCurrency || "USD");

        // Create plain text version
        const plainText = `
Hi ${submissionData.userName || "there"},

Great news! Your job posting "${submissionData.jobTitle}" has been successfully submitted to CSSAwwwards.

Job Details:
- Position: ${submissionData.jobTitle}
- Company: ${submissionData.companyName || "N/A"}
- Job Type: ${submissionData.jobType || "N/A"}
- Category: ${submissionData.category || "N/A"}
- Posted Date: ${submissionDate}

Payment Confirmed:
- Order ID: ${submissionData.paymentOrderID || "N/A"}
- Amount: ${submissionData.paymentAmount || "0.00"} ${submissionData.paymentCurrency || "USD"}
- Status: Verified

What happens next?
1. Your job posting will be reviewed and published within 2-3 business days
2. It will be visible to our global community of designers and developers
3. You'll start receiving applications from qualified candidates
4. The posting will remain active for the duration of your subscription

View Your Job Posts: https://cssawwwards.com/dashboard

Thank you for choosing CSSAwwwards!

Best regards,
The CSSAwwwards Team

Recognition, Credibility, Global Exposure
For agencies, freelancers and all design community.
Copyright © 2025 CSSAwwwards. All rights reserved.
        `.trim();

        const transporter = createTransporter();

        await transporter.sendMail({
            from: '"CSSAwwwards" <noreply@cssawwwards.com>',
            replyTo: '"CSSAwwwards Support" <noreply@cssawwwards.com>',
            to: toEmail,
            subject: `Job "${submissionData.jobTitle}" Successfully Posted - CSSAwwwards`,
            text: plainText,
            html: htmlTemplate,
            headers: {
                'X-Entity-Ref-ID': submissionData.paymentOrderID || 'job-submission',
                'X-Mailer': 'CSSAwwwards Notification System',
                'Organization': 'CSSAwwwards',
                'List-Unsubscribe': '<https://cssawwwards.com/unsubscribe>',
            },
            priority: 'normal',
        });
        console.log("✅ Job submission email sent to:", toEmail);
    } catch (err) {
        console.error("❌ Job submission email error:", err);
    }
};