import { type NextRequest, NextResponse } from "next/server";
import nodemailer from "nodemailer";
import SMTPTransport from "nodemailer/lib/smtp-transport";
import Mail from "nodemailer/lib/mailer";

export async function POST(request: NextRequest) {
    try {
        const body = (await request.json()) as {
            email: string;
            name: string;
            subject: string;
            message: string;
        };
        const { email, name, subject, message } = body;

        console.log('📧 Email request received:', { email, name, subject, messageLength: message.length });

        // Validate input
        if (!email || !name || !subject || !message) {
            console.error('❌ Validation failed: Missing required fields');
            return NextResponse.json(
                { error: "Alle Felder sind erforderlich" },
                { status: 400 },
            );
        }

        // Validate email format
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            console.error('❌ Validation failed: Invalid email format');
            return NextResponse.json(
                { error: "Ungültige E-Mail-Adresse" },
                { status: 400 },
            );
        }

        // Validate message length
        if (message.length < 10) {
            console.error('❌ Validation failed: Message too short');
            return NextResponse.json(
                { error: "Nachricht muss mindestens 10 Zeichen lang sein" },
                { status: 400 },
            );
        }

        const user = process.env.MY_EMAIL ?? "";
        const pass = process.env.MY_PASSWORD ?? "";

        console.log('🔑 Environment check:', { 
            hasEmail: !!user, 
            hasPassword: !!pass,
            emailHost: user.split('@')[1] || 'unknown'
        });

        if (!user || !pass) {
            console.error("❌ Missing email/password environment variables");
            return NextResponse.json(
                { error: "E-Mail-Server nicht konfiguriert" },
                { status: 500 },
            );
        }

        const transportOptions: SMTPTransport.Options = {
            host: "smtp.ionos.de",
            port: 587,
            secure: false,
            requireTLS: true,
            auth: {
                type: "login",
                user,
                pass,
            },
            // Add timeout and debug options
            connectionTimeout: 10000,
            greetingTimeout: 10000,
            socketTimeout: 10000,
        };

        console.log('🚀 Creating transport with options:', {
            host: transportOptions.host,
            port: transportOptions.port,
            secure: transportOptions.secure,
            user: user.split('@')[0] + '@***' // Hide full email in logs
        });

        const transport = nodemailer.createTransport(transportOptions);

        // Verify transport configuration
        try {
            await transport.verify();
            console.log('✅ SMTP connection verified successfully');
        } catch (verifyError) {
            console.error('❌ SMTP verification failed:', verifyError);
            return NextResponse.json(
                { error: "E-Mail-Server-Verbindung fehlgeschlagen" },
                { status: 500 },
            );
        }

        const mailOptions: Mail.Options = {
            from: `"Portfolio Contact" <${user}>`,
            to: "contact@dki.one", // Send to your contact email
            replyTo: email,
            subject: `Portfolio Kontakt: ${subject}`,
            html: `
                <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
                    <h2 style="color: #3b82f6;">Neue Kontaktanfrage von deinem Portfolio</h2>
                    
                    <div style="background: #f8fafc; padding: 20px; border-radius: 8px; margin: 20px 0;">
                        <h3 style="color: #1e293b; margin-top: 0;">Nachricht von ${name}</h3>
                        <p style="color: #475569; margin: 8px 0;"><strong>E-Mail:</strong> ${email}</p>
                        <p style="color: #475569; margin: 8px 0;"><strong>Betreff:</strong> ${subject}</p>
                    </div>
                    
                    <div style="background: #ffffff; padding: 20px; border-radius: 8px; border-left: 4px solid #3b82f6;">
                        <h4 style="color: #1e293b; margin-top: 0;">Nachricht:</h4>
                        <p style="color: #374151; line-height: 1.6; white-space: pre-wrap;">${message}</p>
                    </div>
                    
                    <div style="text-align: center; margin-top: 30px; padding: 20px; background: #f1f5f9; border-radius: 8px;">
                        <p style="color: #64748b; margin: 0; font-size: 14px;">
                            Diese E-Mail wurde automatisch von deinem Portfolio generiert.
                        </p>
                    </div>
                </div>
            `,
            text: `
Neue Kontaktanfrage von deinem Portfolio

Von: ${name} (${email})
Betreff: ${subject}

Nachricht:
${message}

---
Diese E-Mail wurde automatisch von deinem Portfolio generiert.
            `,
        };

        console.log('📤 Sending email...');
        
        const sendMailPromise = () =>
            new Promise<string>((resolve, reject) => {
                transport.sendMail(mailOptions, function (err, info) {
                    if (!err) {
                        console.log('✅ Email sent successfully:', info.response);
                        resolve(info.response);
                    } else {
                        console.error("❌ Error sending email:", err);
                        reject(err.message);
                    }
                });
            });

        const result = await sendMailPromise();
        console.log('🎉 Email process completed successfully');
        
        return NextResponse.json({ 
            message: "E-Mail erfolgreich gesendet",
            messageId: result
        });
        
    } catch (err) {
        console.error("❌ Unexpected error in email API:", err);
        return NextResponse.json({ 
            error: "Fehler beim Senden der E-Mail",
            details: err instanceof Error ? err.message : 'Unbekannter Fehler'
        }, { status: 500 });
    }
}
