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

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

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

export interface ResidentialClientConfirmationData {
  firstName: string;
  contactEmail: string;
  residenceTypes?: string[];
  portName?: string;
}

/**
 * Human-readable phrase for the residence types a lead selected, e.g.
 * "the Two Bedroom Marina Villa and the Four Bedroom Oceanfront Villa".
 * Mirrors the website's phrasing, including its generic fallback.
 */
function residencePhrase(portName: string, types: string[] | undefined): string {
  const list = (types ?? []).filter(Boolean);
  if (list.length === 0) return `a ${portName} Residence`;
  if (list.length === 1) return `the ${list[0]}`;
  if (list.length === 2) return `the ${list[0]} and the ${list[1]}`;
  return `the ${list.slice(0, -1).join(', the ')}, and the ${list[list.length - 1]}`;
}

function ClientConfirmationBody({
  portName,
  firstName,
  contactEmail,
  residencePhraseText,
  accent,
}: {
  portName: string;
  firstName: string;
  contactEmail: string;
  residencePhraseText: string;
  accent: string;
}) {
  return (
    <>
      <Text style={{ marginBottom: '10px', fontSize: '16px' }}>Dear {firstName},</Text>
      <Text style={{ marginBottom: '10px', fontSize: '16px' }}>
        Thank you for expressing interest in {residencePhraseText}. Our team has registered your
        interest, and we will reach out to you very shortly by your preferred method of contact with
        more information.
      </Text>
      <Text style={{ marginBottom: '10px', fontSize: '16px' }}>
        If you have any questions, please feel free to reach out to us at{' '}
        <Link
          href={safeUrl(`mailto:${contactEmail}`)}
          style={{ color: accent, textDecoration: 'underline' }}
        >
          {contactEmail}
        </Link>
        .
      </Text>
      <Text style={{ fontSize: '16px' }}>
        Best regards,
        <br />
        The {portName} Residences Team
      </Text>
    </>
  );
}

export async function residentialClientConfirmation(
  data: ResidentialClientConfirmationData,
  overrides?: RenderOpts,
) {
  const portName = data.portName ?? 'Port Nimara';
  const subject = overrides?.subject?.trim()
    ? overrides.subject
    : `${portName} — Thank You for Your Interest`;
  const accent = brandingPrimaryColor(overrides?.branding);
  const residencePhraseText = residencePhrase(portName, data.residenceTypes);
  const body = await render(
    <ClientConfirmationBody
      portName={portName}
      firstName={data.firstName}
      contactEmail={data.contactEmail}
      residencePhraseText={residencePhraseText}
      accent={accent}
    />,
    { pretty: false },
  );
  const text = [
    `Dear ${data.firstName},`,
    '',
    `Thank you for expressing interest in ${residencePhraseText}. Our team has registered your interest, and we will reach out to you very shortly by your preferred method of contact with more information.`,
    '',
    `If you have any questions, please feel free to reach out to us at ${data.contactEmail}.`,
    '',
    'Best regards,',
    `The ${portName} Residences Team`,
  ].join('\n');
  return {
    subject,
    html: renderShell({ title: subject, body, branding: overrides?.branding }),
    text,
  };
}

export interface ResidentialSalesAlertData {
  fullName: string;
  email: string;
  phone: string;
  residenceTypes?: string[];
  placeOfResidence?: string;
  preferredContactMethod?: 'email' | 'phone';
  notes?: string;
  preferences?: string;
  /**
   * Accepted for backwards-compat with the legacy `/api/public/residential-inquiries`
   * route, but intentionally NOT rendered: residential alerts go to external
   * recipients and must never mention the CRM.
   */
  crmDeepLink?: string;
  portName?: string;
}

function formatPreferredContact(method: 'email' | 'phone' | undefined): string | undefined {
  if (method === 'email') return 'Email';
  if (method === 'phone') return 'Phone call back';
  return undefined;
}

function SalesAlertBody({ portName, data }: { portName: string; data: ResidentialSalesAlertData }) {
  const detailStyle = { margin: '0 0 0', fontSize: '16px' } as const;
  const residenceTypes = (data.residenceTypes ?? []).filter(Boolean);
  const preferredContact = formatPreferredContact(data.preferredContactMethod);
  return (
    <>
      <Text style={{ marginBottom: '10px', fontSize: '16px' }}>Hello,</Text>
      <Text style={{ marginBottom: '10px', fontSize: '16px' }}>
        A new residential enquiry has come in for <strong>{portName}</strong>. {data.fullName} has
        asked us to be in touch - full details below:
      </Text>
      <div style={{ marginBottom: '16px' }}>
        <Text style={detailStyle}>
          <strong>Name:</strong> {data.fullName}
        </Text>
        <Text style={detailStyle}>
          <strong>Email:</strong> {data.email}
        </Text>
        <Text style={detailStyle}>
          <strong>Telephone:</strong> {data.phone}
        </Text>
        {residenceTypes.length > 0 ? (
          <Text style={detailStyle}>
            <strong>Residence type(s):</strong> {residenceTypes.join(', ')}
          </Text>
        ) : null}
        {preferredContact ? (
          <Text style={detailStyle}>
            <strong>Preferred contact:</strong> {preferredContact}
          </Text>
        ) : null}
        {data.placeOfResidence ? (
          <Text style={detailStyle}>
            <strong>Place of residence:</strong> {data.placeOfResidence}
          </Text>
        ) : null}
        {data.preferences ? (
          <Text style={detailStyle}>
            <strong>Preferences:</strong> {data.preferences}
          </Text>
        ) : null}
        {data.notes ? (
          <Text style={detailStyle}>
            <strong>Comments:</strong> {data.notes}
          </Text>
        ) : null}
      </div>
      <Text style={{ fontSize: '16px' }}>- {portName} Residences</Text>
    </>
  );
}

export async function residentialSalesAlert(
  data: ResidentialSalesAlertData,
  overrides?: RenderOpts,
) {
  const portName = data.portName ?? 'Port Nimara';
  const subject = overrides?.subject?.trim()
    ? overrides.subject
    : `New residential enquiry - ${data.fullName}`;
  const body = await render(<SalesAlertBody portName={portName} data={data} />, {
    pretty: false,
  });

  const residenceTypes = (data.residenceTypes ?? []).filter(Boolean);
  const preferredContact = formatPreferredContact(data.preferredContactMethod);
  const text = [
    'Hello,',
    '',
    `A new residential enquiry has come in for ${portName}. ${data.fullName} has asked us to be in touch - full details below:`,
    '',
    `Name: ${data.fullName}`,
    `Email: ${data.email}`,
    `Telephone: ${data.phone}`,
    ...(residenceTypes.length > 0 ? [`Residence type(s): ${residenceTypes.join(', ')}`] : []),
    ...(preferredContact ? [`Preferred contact: ${preferredContact}`] : []),
    ...(data.placeOfResidence ? [`Place of residence: ${data.placeOfResidence}`] : []),
    ...(data.preferences ? [`Preferences: ${data.preferences}`] : []),
    ...(data.notes ? [`Comments: ${data.notes}`] : []),
    '',
    `- ${portName} Residences`,
  ].join('\n');

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