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

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

export interface InquiryClientConfirmationData {
  firstName: string;
  mooringNumber: string | null;
  contactEmail: string;
  portName?: string;
}

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

function ClientConfirmationBody({
  firstName,
  berthText,
  contactEmail,
  portName,
  accent,
}: {
  firstName: string;
  berthText: string;
  contactEmail: string;
  portName: string;
  accent: string;
}) {
  return (
    <>
      <Text style={{ marginBottom: '10px', fontSize: '16px' }}>Dear {firstName},</Text>
      <Text style={{ marginBottom: '10px', fontSize: '16px' }}>
        Thank you for your interest in {berthText}. We&apos;ve noted your enquiry, and a member of
        our team will be in touch shortly through your preferred channel with the details
        you&apos;ve requested.
      </Text>
      <Text style={{ marginBottom: '10px', fontSize: '16px' }}>
        Should anything come to mind in the meantime, please don&apos;t hesitate to write to us at{' '}
        <Link
          href={safeUrl(`mailto:${contactEmail}`)}
          style={{ color: accent, textDecoration: 'underline' }}
        >
          {contactEmail}
        </Link>
        .
      </Text>
      <Text style={{ fontSize: '16px' }}>
        With warm regards,
        <br />
        The {portName} Sales Team
      </Text>
    </>
  );
}

export async function inquiryClientConfirmation(
  data: InquiryClientConfirmationData,
  overrides?: RenderOpts,
) {
  const { firstName, mooringNumber, contactEmail } = data;
  const portName = data.portName ?? 'Port Nimara';
  const berthText = mooringNumber ? `Berth ${mooringNumber}` : `a ${portName} Berth`;
  const subject = overrides?.subject?.trim()
    ? overrides.subject
    : mooringNumber
      ? `Thank you for your interest in Berth ${mooringNumber}`
      : `Thank you for your interest in ${portName}`;
  const accent = brandingPrimaryColor(overrides?.branding);

  const body = await render(
    <ClientConfirmationBody
      firstName={firstName}
      berthText={berthText}
      contactEmail={contactEmail}
      portName={portName}
      accent={accent}
    />,
    { pretty: false },
  );

  const text = [
    `Dear ${firstName},`,
    '',
    `Thank you for your interest in ${berthText}. We've noted your enquiry, and a member of our team will be in touch shortly through your preferred channel with the details you've requested.`,
    '',
    `Should anything come to mind in the meantime, please don't hesitate to write to us at ${contactEmail}.`,
    '',
    'With warm regards,',
    `The ${portName} Sales Team`,
  ].join('\n');

  return {
    subject,
    html: renderShell({ title: subject, body, branding: overrides?.branding }),
    text,
  };
}
