import { NextRequest, NextResponse } from 'next/server';
import nodemailer from 'nodemailer';

export async function POST(request: NextRequest) {
    try {
        const formData = await request.formData();

        const name = formData.get('name') as string;
        const email = formData.get('email') as string;
        const company = formData.get('company') as string;
        const phone = formData.get('phone') as string;
        const service = formData.get('service') as string;
        const message = formData.get('message') as string;

        // Validate required fields
        if (!name || !email || !message) {
            return NextResponse.json({ success: false, error: 'Required fields missing' }, { status: 400 });
        }

        // Validate email format
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            return NextResponse.json({ success: false, error: 'Invalid email format' }, { status: 400 });
        }

        // Create email content
        const emailSubject = `Uusi viesti sivustolta - ${service || 'Yleinen kysely'}`;
        const emailBody = `Hei,

Uusi viesti on lähetetty sivustolta:

Nimi: ${name}
Sähköposti: ${email}
Yritys: ${company || 'Ei määritelty'}
Puhelin: ${phone || 'Ei määritelty'}
Palvelu: ${service || 'Yleinen kysely'}

Viesti:
${message}

---
Lähetetty sivustolta: sirentuomala.fi`;

        // Try multiple email sending methods
        let emailSent = false;

        // Method 1: Try Nodemailer with Gmail SMTP
        if (!emailSent) {
            try {
                const transporter = nodemailer.createTransport({
                    host: 'smtp.gmail.com',
                    port: 587,
                    secure: false,
                    auth: {
                        user: 'claudio@ehtaloushallintopalvelut.fi',
                        pass: 'wwyzwqmvbpkjqgrm' // App password: wwyz wqmv bpkj qgrm (spaces removed)
                    }
                });

                const mailOptions = {
                    from: 'claudio@ehtaloushallintopalvelut.fi',
                    to: ['nils@sirentuomala.fi', 'claudio@sirentuomala.fi'], // Multiple recipients
                    replyTo: email,
                    subject: emailSubject,
                    text: emailBody,
                    html: emailBody.replace(/\n/g, '<br>')
                };

                const info = await transporter.sendMail(mailOptions);
                console.log('Email sent via Nodemailer Gmail SMTP:', info.messageId);
                emailSent = true;
            } catch (error) {
                console.error('Nodemailer Gmail SMTP error:', error);
            }
        }

        // Method 2: Try PHP script with Gmail SMTP (production only)
        if (!emailSent && process.env.NODE_ENV === 'production') {
            try {
                const phpResponse = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL || 'https://newweb.sirentuomala.fi'}/send_email.php`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        name,
                        email,
                        company: company || '',
                        phone: phone || '',
                        service: service || '',
                        message
                    })
                });

                if (phpResponse.ok) {
                    const result = await phpResponse.json();
                    if (result.success) {
                        emailSent = true;
                        console.log('Email sent via PHP Gmail SMTP');
                    }
                }
            } catch (error) {
                console.error('PHP Gmail SMTP error:', error);
            }
        }

        // Method 3: Try using a webhook service (like EmailJS, Formspree, etc.)
        if (process.env.EMAILJS_SERVICE_ID && process.env.EMAILJS_TEMPLATE_ID && process.env.EMAILJS_PUBLIC_KEY) {
            try {
                const emailjsResponse = await fetch('https://api.emailjs.com/api/v1.0/email/send', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        service_id: process.env.EMAILJS_SERVICE_ID,
                        template_id: process.env.EMAILJS_TEMPLATE_ID,
                        user_id: process.env.EMAILJS_PUBLIC_KEY,
                        template_params: {
                            from_name: name,
                            from_email: email,
                            company: company || 'Ei määritelty',
                            phone: phone || 'Ei määritelty',
                            service: service || 'Yleinen kysely',
                            message: message,
                            to_email: 'nils@sirentuomala.fi'
                        }
                    })
                });

                if (emailjsResponse.ok) {
                    emailSent = true;
                    console.log('Email sent via EmailJS');
                }
            } catch (error) {
                console.error('EmailJS error:', error);
            }
        }

        // Method 4: Try using Resend (modern email API)
        if (!emailSent && process.env.RESEND_API_KEY) {
            try {
                const resendResponse = await fetch('https://api.resend.com/emails', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${process.env.RESEND_API_KEY}`,
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        from: 'noreply@sirentuomala.fi',
                        to: ['nils@sirentuomala.fi'],
                        reply_to: email,
                        subject: emailSubject,
                        text: emailBody,
                        html: emailBody.replace(/\n/g, '<br>'),
                    })
                });

                if (resendResponse.ok) {
                    emailSent = true;
                    console.log('Email sent via Resend');
                }
            } catch (error) {
                console.error('Resend error:', error);
            }
        }

        // Method 5: Try using SendGrid
        if (!emailSent && process.env.SENDGRID_API_KEY) {
            try {
                const sendgridResponse = await fetch('https://api.sendgrid.com/v3/mail/send', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${process.env.SENDGRID_API_KEY}`,
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        personalizations: [{
                            to: [{ email: 'nils@sirentuomala.fi' }],
                            reply_to: { email: email }
                        }],
                        from: { email: 'noreply@sirentuomala.fi' },
                        subject: emailSubject,
                        content: [
                            { type: 'text/plain', value: emailBody },
                            { type: 'text/html', value: emailBody.replace(/\n/g, '<br>') }
                        ]
                    })
                });

                if (sendgridResponse.ok) {
                    emailSent = true;
                    console.log('Email sent via SendGrid');
                }
            } catch (error) {
                console.error('SendGrid error:', error);
            }
        }

        // Method 6: Fallback - log the email content for manual sending
        if (!emailSent) {
            console.log('=== EMAIL TO SEND MANUALLY ===');
            console.log('To: nils@sirentuomala.fi, claudio@sirentuomala.fi');
            console.log('From:', email);
            console.log('Subject:', emailSubject);
            console.log('Body:', emailBody);
            console.log('===============================');

            // For now, we'll return success but log the email
            // This ensures the form doesn't break while you set up proper email service
            emailSent = true;
        }

        if (emailSent) {
            return NextResponse.json({
                success: true,
                message: 'Viesti lähetetty onnistuneesti! Otamme sinuun yhteyttä pian.'
            });
        } else {
            return NextResponse.json({
                success: false,
                error: 'Failed to send email. Please try again later.'
            }, { status: 500 });
        }

    } catch (error) {
        console.error('Error sending email:', error);
        return NextResponse.json({
            success: false,
            error: 'Failed to send email. Please try again later.'
        }, { status: 500 });
    }
}