import { Link, Text, render } from '@react-email/components';
import * as React from 'react';

import { brandingPrimaryColor, renderShell, safeUrl, type BrandingShell } from '@/lib/email/shell';

interface RenderOpts {
  branding?: BrandingShell | null;
  subject?: string | null;
}

export interface ContactFormClientConfirmationData {
  firstName: string;
  contactEmail: string;
  portName?: string;
}

function ClientConfirmationBody({
  portName,
  firstName,
  contactEmail,
  accent,
}: {
  portName: string;
  firstName: string;
  contactEmail: string;
  accent: string;
}) {
  return (
    <>
      <Text style={{ marginBottom: '10px', fontSize: '16px' }}>Dear {firstName},</Text>
      <Text style={{ marginBottom: '10px', fontSize: '16px' }}>
        Thank you for contacting {portName}. We have received your message and a member of our team
        will be in touch with you shortly.
      </Text>
      <Text style={{ marginBottom: '10px', fontSize: '16px' }}>
        If you have any questions in the meantime, please feel free to reach out to us at{' '}
        <Link
          href={safeUrl(`mailto:${contactEmail}`)}
          style={{ color: accent, textDecoration: 'underline' }}
        >
          {contactEmail}
        </Link>
        .
      </Text>
      <Text style={{ fontSize: '16px' }}>
        Best regards,
        <br />
        The {portName} Team
      </Text>
    </>
  );
}

export async function contactFormClientConfirmation(
  data: ContactFormClientConfirmationData,
  overrides?: RenderOpts,
) {
  const portName = data.portName ?? 'Port Nimara';
  const subject = overrides?.subject?.trim()
    ? overrides.subject
    : `${portName} — Thank You for Contacting Us`;
  const accent = brandingPrimaryColor(overrides?.branding);
  const body = await render(
    <ClientConfirmationBody
      portName={portName}
      firstName={data.firstName}
      contactEmail={data.contactEmail}
      accent={accent}
    />,
    { pretty: false },
  );
  const text = [
    `Dear ${data.firstName},`,
    '',
    `Thank you for contacting ${portName}. We have received your message and a member of our team will be in touch with you shortly.`,
    '',
    `If you have any questions in the meantime, please feel free to reach out to us at ${data.contactEmail}.`,
    '',
    'Best regards,',
    `The ${portName} Team`,
  ].join('\n');
  return {
    subject,
    html: renderShell({ title: subject, body, branding: overrides?.branding }),
    text,
  };
}
