/**
 * Internal "signing progress" alert — sent to the port's configured
 * signing-notification recipients (e.g. the admin + sales@) so staff get
 * a heads-up every time a party signs and again when a document is fully
 * signed. This is the CRM equivalent of the legacy "Document Signed" /
 * "EOI Complete Update Status" Activepieces flows.
 *
 * Two events:
 *   - `signed`    — a single party just signed (carries who + progress).
 *   - `completed` — all parties have signed.
 *
 * Unlike the signer-facing templates, this one links back into the CRM
 * (deep link to the document) rather than to a signing page — the
 * recipients are staff, not signers.
 */

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

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

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

export interface StatusNotificationData {
  event: 'signed' | 'completed';
  documentLabel: string;
  /** Deal / client name for the salutation + subject context. */
  clientName: string;
  portName: string;
  /** Deep link into the CRM document detail page. */
  crmUrl: string;
  /** For `signed`: who just signed. */
  signerName?: string | null;
  signerRole?: string | null;
  /** For `signed`: progress within the signing order. */
  signedCount?: number;
  totalCount?: number;
}

function roleLabel(role?: string | null): string {
  switch (role) {
    case 'client':
      return 'the client';
    case 'developer':
      return 'the developer';
    case 'approver':
      return 'the approver';
    case 'witness':
      return 'a witness';
    default:
      return 'a signer';
  }
}

function StatusBody({ data, accent }: { data: StatusNotificationData; accent: string }) {
  const isCompleted = data.event === 'completed';
  const progress =
    typeof data.signedCount === 'number' && typeof data.totalCount === 'number'
      ? `${data.signedCount} of ${data.totalCount}`
      : null;

  const heading = isCompleted
    ? `${data.documentLabel} fully signed`
    : `${data.signerName ?? 'A signer'} has signed`;

  return (
    <>
      <Text style={{ marginBottom: '14px', fontSize: '18px', fontWeight: 'bold', color: accent }}>
        {heading}
      </Text>
      {isCompleted ? (
        <Text style={{ marginBottom: '18px', fontSize: '16px', lineHeight: '1.6' }}>
          The {data.documentLabel} for <strong>{data.clientName}</strong> has now been signed by all
          parties. The fully signed PDF has been filed against the deal in the {data.portName} CRM.
        </Text>
      ) : (
        <Text style={{ marginBottom: '18px', fontSize: '16px', lineHeight: '1.6' }}>
          <strong>{data.signerName ?? 'A signer'}</strong> ({roleLabel(data.signerRole)}) has signed
          the {data.documentLabel} for <strong>{data.clientName}</strong>
          {progress ? ` — ${progress} signatures collected so far.` : '.'}
        </Text>
      )}
      <div style={{ textAlign: 'center', margin: '28px 0' }}>
        <Button
          href={safeUrl(data.crmUrl)}
          style={{
            display: 'inline-block',
            backgroundColor: accent,
            color: '#ffffff',
            textDecoration: 'none',
            padding: '14px 36px',
            borderRadius: '5px',
            fontWeight: 'bold',
            fontSize: '16px',
          }}
        >
          View in CRM
        </Button>
      </div>
      <Hr style={{ border: 'none', borderTop: '1px solid #eee', margin: '24px 0 0' }} />
      <Text style={{ fontSize: '13px', color: '#666', lineHeight: '1.5', padding: '14px 0 0' }}>
        Open the deal:{' '}
        <Link
          href={safeUrl(data.crmUrl)}
          style={{ color: accent, textDecoration: 'underline', wordBreak: 'break-all' }}
        >
          {data.crmUrl}
        </Link>
      </Text>
      <Text style={{ fontSize: '13px', color: '#999', lineHeight: '1.5', marginTop: '14px' }}>
        You&apos;re receiving this because you&apos;re on the signing-notification list for{' '}
        {data.portName}. An administrator can change who gets these alerts in CRM settings.
      </Text>
    </>
  );
}

export async function signingStatusNotificationEmail(
  data: StatusNotificationData,
  overrides?: RenderOpts,
): Promise<{ subject: string; html: string; text: string }> {
  const accent = brandingPrimaryColor(overrides?.branding);
  const isCompleted = data.event === 'completed';

  const subject = overrides?.subject
    ? overrides.subject
        .replace(/\{\{documentLabel\}\}/g, data.documentLabel)
        .replace(/\{\{clientName\}\}/g, data.clientName)
        .replace(/\{\{portName\}\}/g, data.portName)
    : isCompleted
      ? `${data.documentLabel} fully signed — ${data.clientName}`
      : `${data.signerName ?? 'A signer'} signed the ${data.documentLabel} — ${data.clientName}`;

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

  const progress =
    typeof data.signedCount === 'number' && typeof data.totalCount === 'number'
      ? ` (${data.signedCount} of ${data.totalCount} signed)`
      : '';
  const text = isCompleted
    ? `The ${data.documentLabel} for ${data.clientName} has been signed by all parties and filed in the ${data.portName} CRM.\n\nView in CRM: ${data.crmUrl}`
    : `${data.signerName ?? 'A signer'} (${roleLabel(data.signerRole)}) has signed the ${data.documentLabel} for ${data.clientName}${progress}.\n\nView in CRM: ${data.crmUrl}`;

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