import { NextRequest, NextResponse } from 'next/server'
import { contactFormSchema } from '@/lib/validation-schemas'
import { rateLimit } from '@/lib/rate-limiter'
import { z } from 'zod'

// Email sending function (using Nodemailer as fallback)
async function sendEmail(data: z.infer<typeof contactFormSchema>) {
  // Check if we have email configuration
  const emailTo = process.env.EMAIL_TO || 'duoteam.dev@email.com'
  const emailFrom = process.env.EMAIL_FROM || 'noreply@duoportfolio.com'

  // Try using Resend first (if available)
  if (process.env.RESEND_API_KEY) {
    try {
      const response = await fetch('https://api.resend.com/emails', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${process.env.RESEND_API_KEY}`,
        },
        body: JSON.stringify({
          from: emailFrom,
          to: emailTo,
          subject: `New Contact Form: ${data.subject}`,
          html: `
            <!DOCTYPE html>
            <html>
              <head>
                <meta charset="utf-8">
                <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, #ef4444, #2563eb); padding: 20px; color: white; border-radius: 8px 8px 0 0; }
                  .content { background: #f9fafb; padding: 30px; border-radius: 0 0 8px 8px; }
                  .field { margin-bottom: 20px; }
                  .label { font-weight: bold; color: #1f2937; margin-bottom: 5px; }
                  .value { color: #4b5563; }
                  .footer { margin-top: 30px; padding-top: 20px; border-top: 1px solid #e5e7eb; color: #6b7280; font-size: 14px; }
                </style>
              </head>
              <body>
                <div class="container">
                  <div class="header">
                    <h2 style="margin: 0;">New Contact Form Submission</h2>
                  </div>
                  <div class="content">
                    <div class="field">
                      <div class="label">Name:</div>
                      <div class="value">${data.name}</div>
                    </div>
                    <div class="field">
                      <div class="label">Email:</div>
                      <div class="value">${data.email}</div>
                    </div>
                    <div class="field">
                      <div class="label">Subject:</div>
                      <div class="value">${data.subject}</div>
                    </div>
                    ${data.projectType ? `
                      <div class="field">
                        <div class="label">Project Type:</div>
                        <div class="value">${data.projectType}</div>
                      </div>
                    ` : ''}
                    <div class="field">
                      <div class="label">Message:</div>
                      <div class="value">${data.message.replace(/\n/g, '<br>')}</div>
                    </div>
                  </div>
                  <div class="footer">
                    <p>This email was sent from the Duo Portfolio contact form.</p>
                    <p>Received: ${new Date().toLocaleString()}</p>
                  </div>
                </div>
              </body>
            </html>
          `,
          text: `
New Contact Form Submission

Name: ${data.name}
Email: ${data.email}
Subject: ${data.subject}
${data.projectType ? `Project Type: ${data.projectType}\n` : ''}
Message:
${data.message}

---
Received: ${new Date().toLocaleString()}
          `,
        }),
      })

      if (!response.ok) {
        const error = await response.json()
        console.error('Resend API error:', error)
        throw new Error('Failed to send email via Resend')
      }

      return { success: true, provider: 'resend' }
    } catch (error) {
      console.error('Resend error, trying fallback:', error)
    }
  }

  // Fallback: Use Nodemailer with SMTP (if configured)
  if (process.env.SMTP_HOST && process.env.SMTP_USER && process.env.SMTP_PASSWORD) {
    try {
      const nodemailer = await import('nodemailer')
      
      const transporter = nodemailer.default.createTransport({
        host: process.env.SMTP_HOST,
        port: parseInt(process.env.SMTP_PORT || '587'),
        secure: process.env.SMTP_PORT === '465',
        auth: {
          user: process.env.SMTP_USER,
          pass: process.env.SMTP_PASSWORD,
        },
      })

      await transporter.sendMail({
        from: emailFrom,
        to: emailTo,
        subject: `New Contact Form: ${data.subject}`,
        html: `
          <h2>New Contact Form Submission</h2>
          <p><strong>Name:</strong> ${data.name}</p>
          <p><strong>Email:</strong> ${data.email}</p>
          <p><strong>Subject:</strong> ${data.subject}</p>
          ${data.projectType ? `<p><strong>Project Type:</strong> ${data.projectType}</p>` : ''}
          <p><strong>Message:</strong></p>
          <p>${data.message.replace(/\n/g, '<br>')}</p>
          <hr>
          <p><small>Received: ${new Date().toLocaleString()}</small></p>
        `,
        text: `
New Contact Form Submission

Name: ${data.name}
Email: ${data.email}
Subject: ${data.subject}
${data.projectType ? `Project Type: ${data.projectType}\n` : ''}
Message:
${data.message}

---
Received: ${new Date().toLocaleString()}
        `,
      })

      return { success: true, provider: 'nodemailer' }
    } catch (error) {
      console.error('Nodemailer error:', error)
      throw error
    }
  }

  // If no email service is configured, just log the submission
  console.log('📧 Contact form submission (no email service configured):', data)
  return { success: true, provider: 'console' }
}

export async function POST(request: NextRequest) {
  try {
    // Rate limiting check
    const ip = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || 'unknown'
    const rateLimitResult = await rateLimit(ip, 'contact-form')
    
    if (!rateLimitResult.success) {
      return NextResponse.json(
        { 
          error: 'Too many requests. Please try again later.',
          retryAfter: rateLimitResult.retryAfter,
        },
        { status: 429 }
      )
    }

    // Parse and validate request body
    const body = await request.json()
    const validationResult = contactFormSchema.safeParse(body)

    if (!validationResult.success) {
      return NextResponse.json(
        { 
          error: 'Validation failed',
          details: validationResult.error.flatten().fieldErrors,
        },
        { status: 400 }
      )
    }

    const data = validationResult.data

    // Send email
    const emailResult = await sendEmail(data)

    // Log submission for tracking
    console.log('✅ Contact form submitted successfully:', {
      name: data.name,
      email: data.email,
      subject: data.subject,
      projectType: data.projectType,
      timestamp: new Date().toISOString(),
      provider: emailResult.provider,
    })

    return NextResponse.json({
      success: true,
      message: 'Your message has been sent successfully. We\'ll get back to you soon!',
    })
  } catch (error) {
    console.error('Contact form API error:', error)
    
    return NextResponse.json(
      { 
        error: 'An error occurred while sending your message. Please try again later.',
        details: process.env.NODE_ENV === 'development' ? String(error) : undefined,
      },
      { status: 500 }
    )
  }
}

// OPTIONS handler for CORS
export async function OPTIONS() {
  return NextResponse.json({}, { status: 200 })
}

