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

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

interface AdminEmailChangeData {
  recipientName?: string;
  newEmail: string;
  changedByDisplayName?: string;
  loginUrl?: string;
  portName?: string;
}

interface RenderOpts {
  branding?: BrandingShell | null;
  /** Admin override for the email subject. Falls back to the template's
   *  default when null/empty. Wired through from email_templates.subject
   *  via getTemplateOverridesForKey() in mailer-config.ts. */
  subject?: string | null;
}

function AdminEmailChangeBody({
  portName,
  newEmail,
  recipientName,
  changedByDisplayName,
  loginUrl,
  accent,
}: AdminEmailChangeData & { portName: string; accent: string }) {
  const greeting = recipientName ? `Dear ${recipientName},` : 'Hello,';
  const adminLine = changedByDisplayName
    ? `${changedByDisplayName} (an administrator)`
    : 'an administrator';
  return (
    <>
      <Text style={{ marginBottom: '10px', fontSize: '18px', fontWeight: 'bold', color: accent }}>
        Your sign-in email has changed
      </Text>
      <Text style={{ marginBottom: '10px', fontSize: '16px', lineHeight: '1.5' }}>{greeting}</Text>
      <Text style={{ marginBottom: '20px', fontSize: '16px', lineHeight: '1.5' }}>
        We&apos;re writing to let you know that {adminLine} has updated the email address linked to
        your {portName} account. Going forward, please sign in with the address below:
      </Text>
      <Text style={{ margin: '20px 0', textAlign: 'center', fontSize: '16px' }}>
        <strong>{newEmail}</strong>
      </Text>
      <Text style={{ fontSize: '16px', marginTop: '8px' }}>
        With warm regards,
        <br />
        <strong>The {portName} Team</strong>
      </Text>
      {loginUrl ? (
        <div style={{ textAlign: 'center', margin: '30px 0' }}>
          <Button
            href={safeUrl(loginUrl)}
            style={{
              display: 'inline-block',
              backgroundColor: accent,
              color: '#ffffff',
              textDecoration: 'none',
              padding: '14px 35px',
              borderRadius: '5px',
              fontWeight: 'bold',
              fontSize: '16px',
            }}
          >
            Sign in
          </Button>
        </div>
      ) : null}
      <Hr style={{ border: 'none', borderTop: '1px solid #eee', margin: '20px 0 0' }} />
      <Text style={{ fontSize: '14px', color: '#666', lineHeight: '1.5', padding: '15px 0 0' }}>
        If this change wasn&apos;t expected, please contact your administrator straight away. The
        previous address (where this message was delivered) is no longer accepted for sign-in.
      </Text>
    </>
  );
}

export async function adminEmailChangeEmail(
  data: AdminEmailChangeData,
  overrides?: RenderOpts,
): Promise<{ subject: string; html: string; text: string }> {
  const portName = data.portName ?? 'Port Nimara';
  const subject = overrides?.subject?.trim()
    ? overrides.subject
    : `Your ${portName} sign-in email has been updated`;
  const accent = brandingPrimaryColor(overrides?.branding);

  const body = await render(
    <AdminEmailChangeBody {...data} portName={portName} accent={accent} />,
    {
      pretty: false,
    },
  );

  const text = [
    `Your sign-in email has changed`,
    '',
    `${data.changedByDisplayName ?? 'An administrator'} has updated the email address linked to your ${portName} account.`,
    `Going forward, please sign in with: ${data.newEmail}`,
    '',
    data.loginUrl ? `Sign in: ${data.loginUrl}` : '',
    '',
    `If this change wasn't expected, please contact your administrator straight away.`,
    '',
    `With warm regards,`,
    `The ${portName} Team`,
  ]
    .filter(Boolean)
    .join('\n');

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