import { render } from '@react-email/components';
import { resend } from './client';
import { WelcomeEmail } from './templates/welcome';

const defaultFrom = process.env.EMAIL_FROM || 'noreply@craftedsaas.com';

export async function sendWelcomeEmail(to: string, name?: string) {
  const html = await render(<WelcomeEmail name={name} />);

  const { data, error } = await resend.emails.send({
    from: defaultFrom,
    to,
    subject: 'Welcome to Crafted SaaS!',
    html,
  });

  if (error) {
    throw new Error(`Failed to send email: ${error.message}`);
  }

  return data;
}

export async function sendPasswordResetEmail(to: string, resetLink: string) {
  const { data, error } = await resend.emails.send({
    from: defaultFrom,
    to,
    subject: 'Reset your password',
    html: `
      <div style="font-family: sans-serif; max-width: 600px; margin: 0 auto;">
        <h1>Reset your password</h1>
        <p>Click the link below to reset your password:</p>
        <a href="${resetLink}" style="display: inline-block; padding: 12px 24px; background: #2563eb; color: white; text-decoration: none; border-radius: 5px;">
          Reset Password
        </a>
        <p style="color: #666; font-size: 14px; margin-top: 20px;">
          If you didn't request this, you can safely ignore this email.
        </p>
      </div>
    `,
  });

  if (error) {
    throw new Error(`Failed to send email: ${error.message}`);
  }

  return data;
}

export async function sendPaymentConfirmationEmail(
  to: string,
  amount: number,
  receiptUrl?: string
) {
  const { data, error } = await resend.emails.send({
    from: defaultFrom,
    to,
    subject: 'Payment Confirmation',
    html: `
      <div style="font-family: sans-serif; max-width: 600px; margin: 0 auto;">
        <h1>Payment Successful ✓</h1>
        <p>Your payment of <strong>$${amount.toFixed(2)}</strong> has been processed successfully.</p>
        ${
          receiptUrl
            ? `<a href="${receiptUrl}" style="display: inline-block; padding: 12px 24px; background: #2563eb; color: white; text-decoration: none; border-radius: 5px; margin-top: 16px;">
            View Receipt
          </a>`
            : ''
        }
        <p style="color: #666; font-size: 14px; margin-top: 20px;">
          Thank you for your business!
        </p>
      </div>
    `,
  });

  if (error) {
    throw new Error(`Failed to send email: ${error.message}`);
  }

  return data;
}
