/**
 * Email Notification Service
 * Handles sending transactional emails like booking confirmations
 */

const { sendMail, getConfig } = require('./email.service');
const emailTemplateRenderer = require('./emailTemplateRenderer.service');
const pdfService = require('./pdf.service');
const invoiceService = require('./invoice.service');
const { getEnv } = require('../utils/envLoader');

/**
 * Send booking confirmation email with invoice PDF attachment
 * @param {Object} booking - Populated booking object with customer details
 */
exports.sendBookingConfirmationEmail = async (booking) => {
    try {
        if (!booking || !booking.customer?.email) {
            console.log('Cannot send email: No customer email found');
            return { success: false, message: 'No customer email' };
        }

        const customerEmail = booking.customer.email;
        const customerName = booking.customer.fullName || 'Valued Customer';

        // Generate invoice data
        let invoiceData;
        try {
            invoiceData = await invoiceService.generateCustomerInvoice(booking._id);
        } catch (invoiceError) {
            console.error('Failed to generate invoice, proceeding without PDF:', invoiceError.message);
            // Send email without attachment if invoice fails
            invoiceData = null;
        }

        // Generate PDF if invoice was created
        let pdfBuffer = null;
        if (invoiceData) {
            try {
                pdfBuffer = await pdfService.generateInvoicePDF(invoiceData, booking);
            } catch (pdfError) {
                console.error('Failed to generate PDF:', pdfError.message);
            }
        }

        // Format pickup date
        const pickupDate = booking.pickupDate
            ? new Date(booking.pickupDate).toLocaleDateString('en-IN', {
                weekday: 'long',
                day: 'numeric',
                month: 'long',
                year: 'numeric'
            })
            : 'To be confirmed';

        // Try to send using email template system
        try {
            const result = await emailTemplateRenderer.sendTemplateEmail(
                'booking_confirmation',
                customerEmail,
                {
                    customerName: customerName,
                    orderId: booking.orderId,
                    pickupLocation: booking.pickupLocation?.address || 'N/A',
                    dropLocation: booking.dropLocation?.address || 'N/A',
                    pickupDate: pickupDate,
                    pickupTime: booking.pickupTime || '10:00 AM',
                    totalFare: (booking.fare?.total || 0).toFixed(2),
                    appName: 'GoCabs'
                },
                {
                    attachments: pdfBuffer ? [{
                        filename: `Invoice_${booking.orderId}.pdf`,
                        content: pdfBuffer,
                        contentType: 'application/pdf'
                    }] : []
                }
            );

            console.log(`Booking confirmation email sent to ${customerEmail} for order ${booking.orderId}`);
            return result;

        } catch (templateError) {
            console.warn('⚠️ Template email failed, using fallback:', templateError.message);
            
            // Fallback to hardcoded template
            const htmlContent = `
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="utf-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
            </head>
            <body style="margin: 0; padding: 0; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f4f4f4;">
                <table width="100%" cellpadding="0" cellspacing="0" style="max-width: 600px; margin: 0 auto; background-color: #ffffff;">
                    <!-- Header -->
                    <tr>
                        <td style="background: linear-gradient(135deg, #ea580c, #f97316); padding: 30px; text-align: center;">
                            <h1 style="color: #ffffff; margin: 0; font-size: 28px;">🚗 Booking Confirmed!</h1>
                            <p style="color: #fff3e6; margin: 10px 0 0 0; font-size: 14px;">Thank you for choosing us</p>
                        </td>
                    </tr>

                    <!-- Greeting -->
                    <tr>
                        <td style="padding: 30px 30px 20px 30px;">
                            <h2 style="color: #333333; margin: 0 0 10px 0;">Hello ${customerName},</h2>
                            <p style="color: #666666; margin: 0; line-height: 1.6;">
                                Your booking has been confirmed and payment received successfully. Here are your trip details:
                            </p>
                        </td>
                    </tr>

                    <!-- Booking Details Card -->
                    <tr>
                        <td style="padding: 0 30px;">
                            <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f8fafc; border-radius: 12px; border: 1px solid #e2e8f0;">
                                <tr>
                                    <td style="padding: 20px;">
                                        <table width="100%" cellpadding="0" cellspacing="0">
                                            <tr>
                                                <td style="padding-bottom: 15px; border-bottom: 1px dashed #cbd5e1;">
                                                    <p style="margin: 0; color: #64748b; font-size: 12px; text-transform: uppercase;">Order ID</p>
                                                    <p style="margin: 5px 0 0 0; color: #ea580c; font-size: 18px; font-weight: bold;">${booking.orderId}</p>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td style="padding: 15px 0;">
                                                    <table width="100%" cellpadding="0" cellspacing="0">
                                                        <tr>
                                                            <td width="30" valign="top">
                                                                <div style="width: 12px; height: 12px; background-color: #22c55e; border-radius: 50%; margin-top: 4px;"></div>
                                                            </td>
                                                            <td>
                                                                <p style="margin: 0; color: #64748b; font-size: 11px; text-transform: uppercase;">Pickup</p>
                                                                <p style="margin: 5px 0 0 0; color: #1e293b; font-size: 14px;">${booking.pickupLocation?.address || 'N/A'}</p>
                                                            </td>
                                                        </tr>
                                                        <tr>
                                                            <td width="30" style="padding-top: 15px;" valign="top">
                                                                <div style="width: 12px; height: 12px; background-color: #ef4444; border-radius: 50%; margin-top: 4px;"></div>
                                                            </td>
                                                            <td style="padding-top: 15px;">
                                                                <p style="margin: 0; color: #64748b; font-size: 11px; text-transform: uppercase;">Drop</p>
                                                                <p style="margin: 5px 0 0 0; color: #1e293b; font-size: 14px;">${booking.dropLocation?.address || 'N/A'}</p>
                                                            </td>
                                                        </tr>
                                                    </table>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td style="padding-top: 15px; border-top: 1px dashed #cbd5e1;">
                                                    <table width="100%" cellpadding="0" cellspacing="0">
                                                        <tr>
                                                            <td width="50%">
                                                                <p style="margin: 0; color: #64748b; font-size: 11px; text-transform: uppercase;">📅 Pickup Date</p>
                                                                <p style="margin: 5px 0 0 0; color: #1e293b; font-size: 13px; font-weight: 600;">${pickupDate}</p>
                                                            </td>
                                                            <td width="50%">
                                                                <p style="margin: 0; color: #64748b; font-size: 11px; text-transform: uppercase;">🕐 Pickup Time</p>
                                                                <p style="margin: 5px 0 0 0; color: #1e293b; font-size: 13px; font-weight: 600;">${booking.pickupTime || '10:00 AM'}</p>
                                                            </td>
                                                        </tr>
                                                    </table>
                                                </td>
                                            </tr>
                                        </table>
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>

                    <!-- Payment Summary -->
                    <tr>
                        <td style="padding: 25px 30px;">
                            <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #ecfdf5; border-radius: 12px; border: 1px solid #a7f3d0;">
                                <tr>
                                    <td style="padding: 20px;">
                                        <table width="100%" cellpadding="0" cellspacing="0">
                                            <tr>
                                                <td>
                                                    <p style="margin: 0; color: #166534; font-weight: bold; font-size: 14px;">✅ Payment Successful</p>
                                                </td>
                                                <td style="text-align: right;">
                                                    <p style="margin: 0; color: #166534; font-size: 22px; font-weight: bold;">₹${(booking.fare?.total || 0).toFixed(2)}</p>
                                                </td>
                                            </tr>
                                        </table>
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>

                    <!-- Important Info -->
                    <tr>
                        <td style="padding: 0 30px 25px 30px;">
                            <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #fef3c7; border-radius: 8px; border-left: 4px solid #f59e0b;">
                                <tr>
                                    <td style="padding: 15px;">
                                        <p style="margin: 0; color: #92400e; font-size: 13px;">
                                            <strong>📢 Important:</strong> Driver and vehicle details will be shared 30 minutes before pickup time via SMS and email.
                                        </p>
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>

                    <!-- CTA Button -->
                    <tr>
                        <td style="padding: 0 30px 30px 30px; text-align: center;">
                            <a href="#" style="display: inline-block; background-color: #ea580c; color: #ffffff; padding: 14px 40px; text-decoration: none; border-radius: 8px; font-weight: bold; font-size: 14px;">View My Booking</a>
                        </td>
                    </tr>

                    <!-- Footer -->
                    <tr>
                        <td style="background-color: #1e293b; padding: 25px 30px; text-align: center;">
                            <p style="margin: 0 0 10px 0; color: #94a3b8; font-size: 12px;">Need Help? Contact our 24/7 support</p>
                            <p style="margin: 0; color: #cbd5e1; font-size: 14px; font-weight: bold;">📞 1800-XXX-XXXX</p>
                            <p style="margin: 15px 0 0 0; color: #64748b; font-size: 11px;">
                                © ${new Date().getFullYear()} GoCabs. All rights reserved.
                            </p>
                        </td>
                    </tr>
                </table>
            </body>
            </html>
            `;

            // Prepare email options
            const emailConfig = await getConfig();
            const mailOptions = {
                from: `"GoCabs Booking" <${emailConfig.user}>`,
                to: customerEmail,
                subject: `✅ Booking Confirmed - ${booking.orderId}`,
                html: htmlContent,
            };

            // Add PDF attachment if available
            if (pdfBuffer) {
                mailOptions.attachments = [
                    {
                        filename: `Invoice_${booking.orderId}.pdf`,
                        content: pdfBuffer,
                        contentType: 'application/pdf'
                    }
                ];
            }

            // Send the email
            const result = await sendMail(mailOptions);

            console.log(`Booking confirmation email sent to ${customerEmail} for order ${booking.orderId}`);

            return {
                success: true,
                messageId: result.messageId,
                email: customerEmail
            };
        }

    } catch (error) {
        console.error('Failed to send booking confirmation email:', error);
        // Don't throw - email failure shouldn't break the payment flow
        return {
            success: false,
            error: error.message
        };
    }
};

/**
 * Send trip completed email with invoice PDF attachment
 * @param {Object} booking - Populated booking object
 */
exports.sendTripCompletedEmail = async (booking) => {
    try {
        if (!booking || !booking.customer?.email) {
            console.log('Cannot send trip completed email: No customer email found');
            return { success: false, message: 'No customer email' };
        }

        const customerEmail = booking.customer.email;
        const customerName = booking.customer.fullName || 'Valued Customer';

        // Generate final invoice data (settled)
        let invoiceData;
        try {
            invoiceData = await invoiceService.generateCustomerInvoice(booking._id);
        } catch (invoiceError) {
            console.error('Failed to generate invoice for completed trip:', invoiceError.message);
            invoiceData = null;
        }

        // Generate PDF
        let pdfBuffer = null;
        if (invoiceData) {
            try {
                pdfBuffer = await pdfService.generateInvoicePDF(invoiceData, booking);
            } catch (pdfError) {
                console.error('Failed to generate PDF for completed trip:', pdfError.message);
            }
        }

        const totalFare = booking.fare?.total || 0;
        const driverName = booking.driver?.fullName || 'Your Driver';

        // Try to send using email template system
        try {
            const result = await emailTemplateRenderer.sendTemplateEmail(
                'trip_completed',
                customerEmail,
                {
                    customerName: customerName,
                    orderId: booking.orderId,
                    driverName: driverName,
                    totalFare: totalFare.toFixed(2),
                    paymentMode: booking.payment?.mode || 'N/A',
                    appName: 'GoCabs'
                },
                {
                    attachments: pdfBuffer ? [{
                        filename: `Receipt_${booking.orderId}.pdf`,
                        content: pdfBuffer,
                        contentType: 'application/pdf'
                    }] : []
                }
            );

            console.log(`Trip completed email sent to ${customerEmail}`);
            return result;

        } catch (templateError) {
            console.warn('⚠️ Template email failed, using fallback:', templateError.message);
            
            // Fallback to hardcoded template
            const htmlContent = `
            <!DOCTYPE html>
            <html>
            <body style="margin: 0; padding: 0; font-family: 'Segoe UI', sans-serif; background-color: #f4f4f4;">
                <table width="100%" cellpadding="0" cellspacing="0" style="max-width: 600px; margin: 0 auto; background-color: #ffffff;">
                    <tr>
                        <td style="background-color: #10b981; padding: 30px; text-align: center;">
                            <h1 style="color: #ffffff; margin: 0; font-size: 28px;">🏁 Trip Completed</h1>
                            <p style="color: #d1fae5; margin: 10px 0 0 0;">We hope you had a great ride!</p>
                        </td>
                    </tr>
                    <tr>
                        <td style="padding: 30px;">
                            <h2 style="color: #333; margin-top: 0;">Hi ${customerName},</h2>
                            <p style="color: #555; line-height: 1.6;">
                                Your trip with <strong>${driverName}</strong> has been completed successfully. 
                                Please find your invoice attached to this email.
                            </p>
                            
                            <div style="background-color: #f9fafb; padding: 20px; border-radius: 8px; margin: 20px 0;">
                                <h3 style="margin: 0 0 15px 0; color: #374151;">Trip Summary</h3>
                                <table width="100%" style="border-collapse: collapse;">
                                    <tr>
                                        <td style="padding: 8px 0; color: #6b7280;">Total Fare</td>
                                        <td style="padding: 8px 0; text-align: right; font-weight: bold; color: #111;">₹${totalFare.toFixed(2)}</td>
                                    </tr>
                                    <tr>
                                        <td style="padding: 8px 0; color: #6b7280;">Payment Mode</td>
                                        <td style="padding: 8px 0; text-align: right; text-transform: uppercase;">${booking.payment?.mode || 'N/A'}</td>
                                    </tr>
                                </table>
                            </div>

                            <p style="text-align: center; margin-top: 30px;">
                                <a href="#" style="background-color: #10b981; color: white; padding: 12px 24px; text-decoration: none; border-radius: 5px; font-weight: bold;">Rate Your Ride</a>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <td style="background-color: #f3f4f6; padding: 20px; text-align: center; color: #6b7280; font-size: 12px;">
                            <p>© ${new Date().getFullYear()} GoCabs. Safe Travels!</p>
                        </td>
                    </tr>
                </table>
            </body>
            </html>
            `;

            const emailConfig = await getConfig();
            const mailOptions = {
                from: `"GoCabs Support" <${emailConfig.user}>`,
                to: customerEmail,
                subject: `✅ Trip Completed - Receipt for ${booking.orderId}`,
                html: htmlContent,
            };

            if (pdfBuffer) {
                mailOptions.attachments = [
                    {
                        filename: `Receipt_${booking.orderId}.pdf`,
                        content: pdfBuffer,
                        contentType: 'application/pdf'
                    }
                ];
            }

            const result = await sendMail(mailOptions);
            console.log(`Trip completed email sent to ${customerEmail}`);
            return { success: true, messageId: result.messageId };
        }

    } catch (error) {
        console.error('Failed to send trip completed email:', error);
        return { success: false, error: error.message };
    }
};
