import { Resend } from 'resend';

const resend = new Resend(process.env.RESEND_API_KEY);

interface SendNotificationParams {
  to: string;
  subject: string;
  title: string;
  message: string;
  actionUrl: string;
  actionText: string;
}

export const sendPortalNotification = async ({
  to,
  subject,
  title,
  message,
  actionUrl,
  actionText
}: SendNotificationParams) => {
  if (!process.env.RESEND_API_KEY) {
    console.warn('⚠️ RESEND_API_KEY is missing. Skipping email dispatch.');
    return;
  }

  const htmlContent = `
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <style>
          body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background-color: #f8fafc; margin: 0; padding: 40px 20px; }
          .container { max-width: 560px; margin: 0 auto; background: #ffffff; border: 1px solid #e2e8f0; border-radius: 16px; padding: 32px; }
          .header { font-size: 20px; font-weight: 800; color: #0f172a; margin-bottom: 12px; }
          .content { font-size: 15px; line-height: 1.6; color: #475569; margin-bottom: 28px; }
          .button { display: inline-block; background-color: #d97706; color: #ffffff !important; font-weight: 700; font-size: 14px; padding: 12px 24px; border-radius: 10px; text-decoration: none; }
          .footer { margin-top: 32px; font-size: 12px; color: #94a3b8; text-align: center; border-t: 1px solid #f1f5f9; padding-top: 16px; }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">${title}</div>
          <div class="content">${message}</div>
          <div>
            <a href="${actionUrl}" class="button">${actionText}</a>
          </div>
          <div class="footer">
            You received this notification because of activity associated with your portal account.
          </div>
        </div>
      </body>
    </html>
  `;

  try {
    const { data, error } = await resend.emails.send({
      from: 'Escrow Portal Notifications <notifications@bookaclassic.pccuae.ae>',
      to: [to],
      subject,
      html: htmlContent
    });

    if (error) {
      console.error(`❌ Resend API Error for ${to}:`, error);
      return;
    }

    console.log(`✅ Email sent successfully via Resend to ${to}: ID ${data?.id}`);
  } catch (error) {
    console.error(`❌ Failed to send email via Resend to ${to}:`, error);
  }
};