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 WelcomeData {
  /** The set-password link (better-auth reset URL landing on /set-password). */
  link: string;
  recipientName?: string;
  /** Human label of the role the account was created with (e.g. "Sales"). */
  roleName?: string;
  /** Full product / app name as branded — e.g. "Port Nimara CRM". Falls back
   *  to "Port Nimara CRM". Used verbatim (no " CRM" is appended). */
  appName?: string;
}

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

function WelcomeBody({
  appName,
  link,
  recipientName,
  roleName,
  accent,
}: {
  appName: string;
  link: string;
  recipientName?: string;
  roleName?: string;
  accent: string;
}) {
  const greeting = recipientName ? `Dear ${recipientName},` : 'Welcome aboard,';
  const roleClause = roleName ? ` with the ${roleName} role` : '';
  return (
    <>
      <Text style={emailStyle.title(accent)}>Welcome to {appName}</Text>
      <Text style={emailStyle.paragraph}>{greeting}</Text>
      <Text style={emailStyle.paragraph}>
        An account has been created for you in {appName}
        {roleClause}. To get started, set your password using the button below — then sign in with
        this email address.
      </Text>
      <div style={emailStyle.buttonRow}>
        <Button href={safeUrl(link)} style={emailStyle.button(accent)}>
          Set your password
        </Button>
      </div>
      <Text style={emailStyle.signoff}>
        See you inside,
        <br />
        <strong>The {appName} Team</strong>
      </Text>
      <Hr style={emailStyle.divider} />
      <Text style={emailStyle.finePrint}>
        For security this link will expire after a short while. If it&apos;s no longer valid, ask
        your administrator to send you a new one.
        <br />
        <br />
        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>
    </>
  );
}

/**
 * Welcome / set-your-password email for an admin-created CRM user. Distinct from
 * the self-service "Reset your password" email — a brand-new user has nothing to
 * reset. Wraps the same better-auth reset link that the /set-password page
 * consumes, but in onboarding framing.
 */
export async function crmWelcomeEmail(
  data: WelcomeData,
  overrides?: RenderOpts,
): Promise<{ subject: string; html: string; text: string }> {
  const appName = data.appName ?? 'Port Nimara CRM';
  const subject = overrides?.subject?.trim()
    ? overrides.subject
    : `Welcome to ${appName} — set your password`;
  const accent = brandingPrimaryColor(overrides?.branding);

  const body = await render(
    <WelcomeBody
      appName={appName}
      link={data.link}
      recipientName={data.recipientName}
      roleName={data.roleName}
      accent={accent}
    />,
    { pretty: false },
  );

  const text = [
    `Welcome to ${appName}`,
    '',
    `An account has been created for you${data.roleName ? ` with the ${data.roleName} role` : ''}.`,
    `Set your password to get started: ${data.link}`,
    '',
    `For security this link will expire after a short while — if it's no longer valid, ask your administrator to send a new one.`,
    '',
    `See you inside,`,
    `The ${appName} Team`,
  ].join('\n');

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