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 ? `Hello ${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 was changed
      </Text>
      <Text style={{ marginBottom: '10px', fontSize: '16px', lineHeight: '1.5' }}>{greeting}</Text>
      <Text style={{ marginBottom: '20px', fontSize: '16px', lineHeight: '1.5' }}>
        {adminLine} just updated the email address linked to your {portName} account. From now on,
        please sign in with the new address below:
      </Text>
      <Text style={{ margin: '20px 0', textAlign: 'center', fontSize: '16px' }}>
        <strong>{newEmail}</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 you weren&apos;t expecting this change, contact your administrator immediately. Your old
        address (the one this message was sent to) can no longer be used to sign in.
      </Text>
      <Text style={{ fontSize: '16px', marginTop: '30px' }}>
        Thanks,
        <br />
        <strong>{portName}</strong>
      </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
    : `An administrator updated your ${portName} sign-in email`;
  const accent = brandingPrimaryColor(overrides?.branding);

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

  const text = [
    `Your sign-in email was changed`,
    '',
    `${data.changedByDisplayName ?? 'An administrator'} updated the email linked to your ${portName} account.`,
    `From now on, sign in with: ${data.newEmail}`,
    '',
    data.loginUrl ? `Sign in: ${data.loginUrl}` : '',
    '',
    `If you weren't expecting this change, contact your administrator immediately.`,
  ]
    .filter(Boolean)
    .join('\n');

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