import nodemailer from 'nodemailer';

const transporter = nodemailer.createTransport({
    host: process.env.SMTP_HOST || 'smtp.example.com',
    port: parseInt(process.env.SMTP_PORT || '587'),
    secure: process.env.SMTP_SECURE === 'true', // true for 465, false for other ports
    auth: {
        user: process.env.SMTP_USER || 'user@example.com',
        pass: process.env.SMTP_PASS || 'pass',
    },
});

export const sendEmail = async (to: string, subject: string, html: string) => {
    try {
        const info = await transporter.sendMail({
            from: `"Nordic Storium" <${process.env.SMTP_FROM || 'noreply@nordicstorium.com'}>`,
            to,
            subject,
            html,
        });
        console.log('Email sent: %s', info.messageId);
        return true;
    } catch (error) {
        console.error('Email send error:', error);
        return false;
    }
};

const premiumTemplate = (content: string) => `
    <div style="font-family: 'Inter', -apple-system, sans-serif; max-width: 600px; margin: 40px auto; border: 1px solid #000000; color: #000000; background: #ffffff; overflow: hidden;">
        <div style="background: linear-gradient(135deg, #0a192f 0%, #020c1b 100%); padding: 40px; text-align: center; border-bottom: 1px solid #000000;">
            <h1 style="font-size: 16px; font-weight: 900; text-transform: uppercase; letter-spacing: 4px; margin: 0; color: #ffffff;">Nordic Storium</h1>
        </div>
        
        <div style="padding: 50px 40px;">
            ${content}
        </div>
        
        <div style="background: linear-gradient(135deg, #0a192f 0%, #020c1b 100%); padding: 40px; border-top: 1px solid #000000; text-align: center;">
            <div style="font-size: 10px; color: #ffffff; text-transform: uppercase; letter-spacing: 2px; font-weight: 900;">
                &copy; ${new Date().getFullYear()} Nordic Storium &mdash; Stockholm, Sweden.
            </div>
            <div style="margin-top: 15px; font-size: 10px; color: #a0aec0; text-transform: uppercase; letter-spacing: 1px;">
                Naturens kraft möter tidlös design.
            </div>
        </div>
    </div>
`;

export const sendVerificationEmail = async (email: string, token: string) => {
    const url = `${process.env.NEXT_PUBLIC_APP_URL}/api/auth/verify?token=${token}`;
    const content = `
        <h2 style="font-size: 18px; font-weight: 800; text-transform: uppercase; margin-bottom: 20px;">Verifiera Konto</h2>
        <p style="font-size: 14px; line-height: 1.6; color: #666666; margin-bottom: 30px;">
            Tack för att du anslutit dig till Nordic Storium. För att aktivera ditt konto behöver du bekräfta din e-postadress.
        </p>
        <a href="${url}" style="display: block; background: #000000; color: #ffffff; text-align: center; padding: 16px; text-decoration: none; font-weight: 700; font-size: 13px; text-transform: uppercase; letter-spacing: 1px; border-radius: 4px;">
            Bekräfta E-post
        </a>
    `;
    return sendEmail(email, 'Verifiera din e-post - Nordic Storium', premiumTemplate(content));
};

export const sendWelcomeNewsletterEmail = async (email: string, name: string) => {
    const content = `
        <h2 style="font-size: 16px; font-weight: 800; text-transform: uppercase; margin-bottom: 20px; letter-spacing: 1px;">Välkommen ${name}</h2>
        <p style="font-size: 14px; line-height: 1.7; color: #444444; margin-bottom: 30px;">
            Du prenumererar nu på Nordic Storiums exklusiva nyhetsbrev. Du kommer att få de senaste nyheterna om nordisk design och unika erbjudanden direkt i din inkorg.
        </p>
        <p style="font-size: 14px; font-style: italic; color: #000; margin: 30px 0;">
            "Ge möbler ett andra liv – där hållbarhet möter smart ekonomi"
        </p>
    `;
    return sendEmail(email, 'Välkommen till nyhetsbrevet - Nordic Storium', premiumTemplate(content));
};

export const sendPasswordResetEmail = async (email: string, token: string) => {
    const resetUrl = `${process.env.NEXT_PUBLIC_APP_URL}/reset-password/${token}`;
    const content = `
        <h2 style="font-size: 16px; font-weight: 800; text-transform: uppercase; margin-bottom: 20px; letter-spacing: 1px;">Återställ Lösenord</h2>
        <p style="font-size: 14px; line-height: 1.7; color: #444444; margin-bottom: 30px;">
            Vi har mottagit en begäran om att återställa lösenordet för ditt konto. Klicka på knappen nedan för att välja ett nytt lösenord.
        </p>
        <a href="${resetUrl}" style="display: block; background: #000000; color: #ffffff; text-align: center; padding: 18px; text-decoration: none; font-weight: 700; font-size: 12px; text-transform: uppercase; letter-spacing: 2px; border-radius: 4px;">
            Välj Nytt Lösenord
        </a>
        <p style="font-size: 12px; color: #999999; margin-top: 40px;">
            Länken är giltig i 1 timme. Om du inte begärt detta kan du säkert bortse från mejlet.
        </p>
    `;
    return sendEmail(email, 'Återställ ditt lösenord - Nordic Storium', premiumTemplate(content));
};

export const sendContactEmail = async (name: string, email: string, subject: string, message: string) => {
    const adminEmail = process.env.CONTACT_EMAIL || 'admin@nordicstorium.com';
    const content = `
        <h2 style="font-size: 16px; font-weight: 800; text-transform: uppercase; margin-bottom: 20px; letter-spacing: 1px;">Nytt Kontaktmeddelande</h2>
        <div style="background: #f7fafc; padding: 20px; border-left: 4px solid #000000; margin-bottom: 30px;">
            <p style="font-size: 14px; margin: 0 0 10px 0;"><strong>Från:</strong> ${name}</p>
            <p style="font-size: 14px; margin: 0 0 10px 0;"><strong>Email:</strong> <a href="mailto:${email}" style="color: #000000;">${email}</a></p>
            <p style="font-size: 14px; margin: 0;"><strong>Ämne:</strong> ${subject}</p>
        </div>
        <div style="background: #ffffff; padding: 20px; border: 1px solid #e2e8f0;">
            <h3 style="font-size: 14px; font-weight: 700; text-transform: uppercase; margin: 0 0 15px 0; letter-spacing: 1px;">Meddelande:</h3>
            <p style="font-size: 14px; line-height: 1.7; color: #444444; white-space: pre-wrap;">${message}</p>
        </div>
        <div style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #e2e8f0;">
            <p style="font-size: 12px; color: #999999;">Svara på detta meddelande genom att maila direkt till: <a href="mailto:${email}" style="color: #000000;">${email}</a></p>
        </div>
    `;
    return sendEmail(adminEmail, `Kontaktformulär: ${subject}`, premiumTemplate(content));
};

export const sendSellFurnitureEmail = async (
    name: string,
    email: string,
    phone: string,
    address: string,
    message: string,
    images: { filename: string; content: Buffer; contentType: string }[]
) => {
    const adminEmail = process.env.CONTACT_EMAIL || 'admin@nordicstorium.com';
    const content = `
        <h2 style="font-size: 16px; font-weight: 800; text-transform: uppercase; margin-bottom: 20px; letter-spacing: 1px;">Försäljning av Möbler</h2>
        <div style="background: #f7fafc; padding: 20px; border-left: 4px solid #000000; margin-bottom: 30px;">
            <p style="font-size: 14px; margin: 0 0 10px 0;"><strong>Från:</strong> ${name}</p>
            <p style="font-size: 14px; margin: 0 0 10px 0;"><strong>Email:</strong> <a href="mailto:${email}" style="color: #000000;">${email}</a></p>
            <p style="font-size: 14px; margin: 0 0 10px 0;"><strong>Telefon:</strong> ${phone}</p>
            <p style="font-size: 14px; margin: 0;"><strong>Adress:</strong> ${address}</p>
        </div>
        <div style="background: #ffffff; padding: 20px; border: 1px solid #e2e8f0;">
            <h3 style="font-size: 14px; font-weight: 700; text-transform: uppercase; margin: 0 0 15px 0; letter-spacing: 1px;">Meddelande:</h3>
            <p style="font-size: 14px; line-height: 1.7; color: #444444; white-space: pre-wrap;">${message}</p>
        </div>
        <div style="margin-top: 30px; padding: 20px; background: #f7fafc; border: 1px solid #e2e8f0;">
            <p style="font-size: 12px; color: #666666; margin: 0;"><strong>Bifogade bilder:</strong> ${images.length} st</p>
        </div>
        <div style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #e2e8f0;">
            <p style="font-size: 12px; color: #999999;">Svara på detta meddelande genom att maila direkt till: <a href="mailto:${email}" style="color: #000000;">${email}</a></p>
        </div>
    `;

    try {
        const attachments = images.map(img => ({
            filename: img.filename,
            content: img.content,
            contentType: img.contentType
        }));

        const info = await transporter.sendMail({
            from: `"Nordic Storium" <${process.env.SMTP_FROM || 'noreply@nordicstorium.com'}>`,
            to: adminEmail,
            subject: `Försäljning av Möbler: ${name}`,
            html: premiumTemplate(content),
            attachments
        });
        console.log('Sell furniture email sent: %s', info.messageId);
        return true;
    } catch (error) {
        console.error('Email send error:', error);
        return false;
    }
};
