'use server';

import { sendEmail } from '@/lib/mail/mailer';
import { render, ContactFormNotification, ConfirmationMessage } from '@mintel/mail';
import React from 'react';

export async function sendContactFormAction(formData: FormData) {
    const name = formData.get('name') as string;
    const email = formData.get('email') as string;
    const message = formData.get('message') as string;
    const productName = formData.get('productName') as string | null;

    if (!name || !email || !message) {
        console.warn('Missing required fields in contact form');
        return { success: false, error: 'Missing required fields' };
    }

    // 1. Save to CMS
    try {
        const { getPayload } = await import('payload');
        const configPromise = (await import('@payload-config')).default;
        const payload = await getPayload({ config: configPromise });

        await payload.create({
            collection: 'form-submissions',
            data: {
                name,
                email,
                message,
                type: productName ? 'product_quote' : 'contact',
                productName: productName || undefined,
            },
        });

        console.log('Successfully saved form submission to Payload CMS');
    } catch (error) {
        console.error('Failed to store submission in Payload CMS', { error });
    }

    // 2. Send Emails
    console.log('Sending branded emails', { email, productName });

    const notificationSubject = productName
        ? `Product Inquiry: ${productName}`
        : 'New Contact Form Submission';
    const confirmationSubject = 'Thank you for your inquiry';

    try {
        // 2a. Send notification to Mintel/Client
        const notificationHtml = await render(
            React.createElement(ContactFormNotification, {
                name,
                email,
                message,
                productName: productName || undefined,
            }),
        );

        const notificationResult = await sendEmail({
            replyTo: email,
            subject: notificationSubject,
            html: notificationHtml,
        });

        if (!notificationResult.success) {
            console.error('Notification email FAILED', { error: notificationResult.error });
        }

        // 2b. Send confirmation to Customer
        const confirmationHtml = await render(
            React.createElement(ConfirmationMessage, {
                name,
                clientName: 'Cable Creations',
            }),
        );

        const confirmationResult = await sendEmail({
            to: email,
            subject: confirmationSubject,
            html: confirmationHtml,
        });

        if (!confirmationResult.success) {
            console.error('Confirmation email FAILED', { error: confirmationResult.error });
        }

        return { success: true };
    } catch (error) {
        const errorMsg = error instanceof Error ? error.message : String(error);
        console.error('Failed to send branded emails', { error: errorMsg });
        return { success: false, error: errorMsg };
    }
}
