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

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

interface InviteData {
  link: string;
  ttlHours: number;
  recipientName?: string;
  isSuperAdmin: boolean;
  /** Display name for the port - falls back to "Port Nimara" so the
   *  pre-multi-tenant default still reads correctly. */
  portName?: string;
}

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

function InviteBody({
  portName,
  link,
  ttlHours,
  recipientName,
  role,
  accent,
}: {
  portName: string;
  link: string;
  ttlHours: number;
  recipientName?: string;
  role: string;
  accent: string;
}) {
  const greeting = recipientName ? `Dear ${recipientName},` : 'Welcome aboard,';
  return (
    <>
      <Text style={emailStyle.title(accent)}>Welcome to the {portName} CRM</Text>
      <Text style={emailStyle.paragraph}>{greeting}</Text>
      <Text style={emailStyle.paragraph}>
        You&apos;ve been invited to join the {portName} CRM as a {role}. Use the button below to set
        your password and activate your account at your convenience - the link will remain valid for{' '}
        {ttlHours} hours.
      </Text>
      <Text style={emailStyle.signoff}>
        With warm regards,
        <br />
        <strong>The {portName} Team</strong>
      </Text>
      <div style={emailStyle.buttonRow}>
        <Button href={safeUrl(link)} style={emailStyle.button(accent)}>
          Set up your account
        </Button>
      </div>
      <Hr style={emailStyle.divider} />
      <Text style={emailStyle.finePrint}>
        If the button doesn&apos;t work, paste this link into your browser:
        <br />
        <Link
          href={safeUrl(link)}
          style={{ color: accent, textDecoration: 'underline', wordBreak: 'break-all' }}
        >
          {link}
        </Link>
      </Text>
    </>
  );
}

export async function crmInviteEmail(
  data: InviteData,
  overrides?: RenderOpts,
): Promise<{ subject: string; html: string; text: string }> {
  const portName = data.portName ?? 'Port Nimara';
  const subject = overrides?.subject?.trim()
    ? overrides.subject
    : `You're invited to the ${portName} CRM`;
  const role = data.isSuperAdmin ? 'super administrator' : 'administrator';
  const accent = brandingPrimaryColor(overrides?.branding);

  const body = await render(
    <InviteBody
      portName={portName}
      link={data.link}
      ttlHours={data.ttlHours}
      recipientName={data.recipientName}
      role={role}
      accent={accent}
    />,
    { pretty: false },
  );

  const text = [
    `Welcome to the ${portName} CRM`,
    '',
    `You've been invited to join the ${portName} CRM as a ${role}.`,
    `Set up your account: ${data.link}`,
    '',
    `The link will remain valid for ${data.ttlHours} hours.`,
    '',
    `With warm regards,`,
    `The ${portName} Team`,
  ].join('\n');

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