import express from 'express';
import nodemailer from 'nodemailer';
import { verifyRecaptcha } from '../utils/recaptchaService.js';

const router = express.Router();

// Create email transporter - Updated for CPanel email
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
  });
};

// POST /api/contact - Handle contact form submission
router.post('/', async (req, res) => {
  try {
    const { name, email, website, subject, comment, recaptchaToken } = req.body;

    console.log('📧 Contact form submission received:', { name, email, subject });

    // Verify reCAPTCHA first
    try {
      await verifyRecaptcha(recaptchaToken, 'contact', 0.5);
    } catch (recaptchaError) {
      console.error('❌ reCAPTCHA verification failed:', recaptchaError.message);
      return res.status(400).json({ 
        message: "reCAPTCHA verification failed. Please try again." 
      });
    }

    // Validation
    if (!name || !email || !subject || !comment) {
      return res.status(400).json({ 
        message: 'Please fill in all required fields' 
      });
    }

    // Email validation
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      return res.status(400).json({ 
        message: 'Please provide a valid email address' 
      });
    }

    // Create email content
    const htmlContent = `
      <!DOCTYPE html>
      <html>
      <head>
        
      </head>
      <body>
        <div class="container">

          <div class="header">
            <h1>New Contact Form Submission</h1>
          </div>
          <div class="content">
            <div class="field">
              <div class="label">Subject:</div>
              <div class="value">${subject}</div>
            </div>
            <div class="field">
              <div class="label">Name:</div>
              <div class="value">${name}</div>
            </div>
            <div class="field">
              <div class="label">Email:</div>
              <div class="value">${email}</div>
            </div>
            ${website ? `
            <div class="field">
              <div class="label">Website:</div>
              <div class="value"><a href="${website}" target="_blank">${website}</a></div>
            </div>
            ` : ''}
            <div class="field">
              <div class="label">Message:</div>
              <div class="value">${comment.replace(/\n/g, '<br>')}</div>
            </div>
          </div>
          <div class="footer">
            <p>This email was sent from CSSAWWWARDS Contact Form</p>
            <p>Reply directly to this email to respond to ${name}</p>
          </div>
        </div>
      </body>
      </html>
    `;

    try {
      // Create transporter
      const transporter = createTransporter();

      // Send email to support
      const mailOptions = {
        from: `"CSSAWWWARDS Contact Form" <noreply@cssawwwards.com>`,
        to: 'developer0031@gmail.com', 
        replyTo: 'supports@cssawwwards.com',
        subject: `[CSSAWWWARDS Contact] ${subject} - ${name}`,
        html: htmlContent,
        text: `
Subject: ${subject}
Name: ${name}
Email: ${email}
${website ? `Website: ${website}` : ''}

Message:
${comment}
        `,
      };

      // Send email
      await transporter.sendMail(mailOptions);
      console.log('✅ Contact form email sent to admin');

      // Send confirmation email to user
      const confirmationHtml = `
        <!DOCTYPE html>
        <html>
        <head>
          <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background-color: #000; color: #fff; padding: 30px; text-align: center; }
            .content { padding: 30px; background-color: #f9f9f9; }
            .footer { text-align: center; padding: 20px; color: #777; font-size: 12px; }
          </style>
        </head>
        <body>
          <div class="container">
            <div class="header">
              <h1>Thank You for Contacting Us!</h1>
            </div>
            <div class="content">
              <p>Hi ${name},</p>
              <p>Thank you for reaching out to CSSAWWWARDS. We have received your message and will get back to you as soon as possible.</p>
              <p><strong>Your message:</strong></p>
              <p style="background-color: #fff; padding: 15px; border-left: 3px solid #000;">
                ${comment.replace(/\n/g, '<br>')}
              </p>
              <p>If you have any urgent concerns, please don't hesitate to reach out directly at Cssawwwards@gmail.com.</p>
              <p>Best regards,<br><strong>The CSSAWWWARDS Team</strong></p>
            </div>
            <div class="footer">
              <p>© 2025 CSSAWWWARDS. All rights reserved.</p>
            </div>
          </div>
        </body>
        </html>
      `;

      const confirmationMailOptions = {
        from: `"CSSAWWWARDS" <${process.env.GOOGLE_APP_EMAIL}>`,
        to: email,
        subject: 'We received your message - CSSAWWWARDS',
        html: confirmationHtml,
        text: `
Hi ${name},

Thank you for reaching out to CSSAWWWARDS. We have received your message and will get back to you as soon as possible.

Your message:
${comment}

If you have any urgent concerns, please don't hesitate to reach out directly at Cssawwwards@gmail.com.

Best regards,
The CSSAWWWARDS Team
        `,
      };

      await transporter.sendMail(confirmationMailOptions);
      console.log('✅ Confirmation email sent to user');

    } catch (emailError) {
      console.error('❌ Email sending failed:', emailError.message);
      console.error('Full error:', emailError);
      // Don't fail the request if email fails - still return success
      // The message was received, email is just a notification
    }

    res.status(200).json({ 
      message: 'Message sent successfully',
      success: true
    });

  } catch (error) {
    console.error('❌ Contact form error:', error);
    res.status(500).json({ 
      message: 'Failed to send message. Please try again later.',
      error: error.message 
    });
  }
});

export default router;
