import { NextResponse } from 'next/server'
import nodemailer from 'nodemailer'

export async function POST(request: Request) {
  try {
    const body = await request.json()
    const { fullName, email, phone } = body

    // Create HTML email content
    const htmlContent = `
<!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: linear-gradient(135deg, #FF8C00 0%, #FF6B00 100%); color: white; padding: 20px; border-radius: 5px 5px 0 0; }
        .content { border: 1px solid #ddd; padding: 20px; border-radius: 0 0 5px 5px; }
        .field { margin: 15px 0; }
        .label { font-weight: bold; color: #FF8C00; }
        .value { margin-top: 5px; color: #333; }
        .footer { margin-top: 30px; padding-top: 20px; border-top: 1px solid #ddd; font-size: 12px; color: #666; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h2>New Course Enrollment Request</h2>
        </div>
        <div class="content">
            <p>You have received a new enrollment request for the AI Accelerator Program. Here are the details:</p>
            
            <div class="field">
                <div class="label">Full Name:</div>
                <div class="value">${fullName}</div>
            </div>
            
            <div class="field">
                <div class="label">Email Address:</div>
                <div class="value">${email}</div>
            </div>
            
            <div class="field">
                <div class="label">Phone Number:</div>
                <div class="value">${phone}</div>
            </div>
            
            <div class="field">
                <div class="label">Course:</div>
                <div class="value">Mastering RAG - From Foundations to Advanced Systems</div>
            </div>
            
            <div class="field">
                <div class="label">Early Bird Price:</div>
                <div class="value">₹9,999</div>
            </div>
            
            <div class="field">
                <div class="label">Submission Time:</div>
                <div class="value">${new Date().toLocaleString()}</div>
            </div>
            
            <p style="margin-top: 30px; background: #f5f5f5; padding: 15px; border-radius: 5px;">
                <strong>Action Required:</strong> Please contact the applicant at <strong>${email}</strong> or <strong>${phone}</strong> to complete the enrollment process and provide further details about the program.
            </p>
            
            <div class="footer">
                <p>This is an automated email from the Rethinksoft AI Accelerator Program website. Please do not reply to this email.</p>
            </div>
        </div>
    </div>
</body>
</html>
    `

    const textContent = `
New Course Enrollment Request

Full Name: ${fullName}
Email: ${email}
Phone: ${phone}

Course: Mastering RAG - From Foundations to Advanced Systems
Early Bird Price: ₹9,999
Submission Time: ${new Date().toLocaleString()}

This enrollment request was submitted through the Rethinksoft AI Accelerator Program website.

Please contact the student to complete the enrollment process.
    `

    // Check if we have email configuration
    const smtpHost = process.env.SMTP_HOST
    const smtpPort = process.env.SMTP_PORT
    const smtpUser = process.env.SMTP_USER
    const smtpPassword = process.env.SMTP_PASSWORD
    const fromEmail = process.env.FROM_EMAIL || 'noreply@rethinksoft.com'

    // If SMTP credentials are configured, send via SMTP
    if (smtpHost && smtpPort && smtpUser && smtpPassword) {
      const transporter = nodemailer.createTransport({
        host: smtpHost,
        port: parseInt(smtpPort),
        secure: true,
        auth: {
          user: smtpUser,
          pass: smtpPassword,
        },
      })

      await transporter.sendMail({
        from: fromEmail,
        to: 'info@rethinksoft.com',
        replyTo: email,
        subject: `New Course Enrollment: ${fullName}`,
        html: htmlContent,
        text: textContent,
      })

      // Also send confirmation to the applicant
      await transporter.sendMail({
        from: fromEmail,
        to: email,
        subject: 'Enrollment Confirmation - Rethinksoft AI Accelerator Program',
        html: `
<!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: linear-gradient(135deg, #FF8C00 0%, #FF6B00 100%); color: white; padding: 20px; border-radius: 5px 5px 0 0; }
        .content { border: 1px solid #ddd; padding: 20px; border-radius: 0 0 5px 5px; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h2>Thank You for Enrolling!</h2>
        </div>
        <div class="content">
            <p>Dear ${fullName},</p>
            
            <p>Thank you for submitting your enrollment request for the <strong>AI Accelerator Program: Mastering RAG - From Foundations to Advanced Systems</strong>.</p>
            
            <p>We have received your application with the following details:</p>
            <ul>
                <li><strong>Name:</strong> ${fullName}</li>
                <li><strong>Email:</strong> ${email}</li>
                <li><strong>Phone:</strong> ${phone}</li>
                <li><strong>Course Price:</strong> ₹9,999 (Early Bird)</li>
            </ul>
            
            <p>Our team will review your enrollment and contact you within 24 hours to confirm your participation and provide you with course materials and further details.</p>
            
            <p><strong>Program Details:</strong></p>
            <ul>
                <li>Duration: 6 weeks</li>
                <li>Schedule: 7 Mar – 15 Apr 2026</li>
                <li>Live Sessions: 4 hours/week</li>
                <li>Format: Live, Interactive, Cohort-based</li>
            </ul>
            
            <p>If you have any questions in the meantime, feel free to reach out to us at <strong>info@rethinksoft.com</strong> or call us.</p>
            
            <p>Best regards,<br/>
            <strong>Rethinksoft AI Team</strong><br/>
            <em>Building Advanced AI Solutions</em></p>
        </div>
    </div>
</body>
</html>
        `,
        text: `Dear ${fullName},

Thank you for submitting your enrollment request for the AI Accelerator Program: Mastering RAG - From Foundations to Advanced Systems.

We have received your application. Our team will contact you within 24 hours to confirm your participation.

Best regards,
Rethinksoft AI Team`,
      })
    } else {
      // Fallback: log to console when email service is not configured
      console.log('📧 ENROLLMENT REQUEST (Email service not configured)')
      console.log('To: info@rethinksoft.com')
      console.log('From:', email)
      console.log('Subject: New Course Enrollment:', fullName)
      console.log('\n--- EMAIL CONTENT ---')
      console.log(textContent)
      console.log('--- END EMAIL ---\n')
    }

    // Return success response
    return NextResponse.json({
      success: true,
      message: `Thank you for enrolling! We've sent a confirmation to ${email}. Our team will contact you within 24 hours.`,
    })
  } catch (error) {
    console.error('Error processing enrollment:', error)
    return NextResponse.json(
      { error: 'Failed to process enrollment request. Please try again.' },
      { status: 500 }
    )
  }
}
