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

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

interface DigestData {
  portName: string;
  recipientName: string;
  items: Array<{
    type: string;
    title: string;
    description: string | null;
    link: string | null;
    createdAt: Date;
  }>;
  totalUnread: number;
  inboxLink: string;
}

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

const TYPE_LABELS: Record<string, string> = {
  reminder_due: 'Reminder due',
  reminder_overdue: 'Reminder overdue',
  new_registration: 'New inquiry',
  eoi_signed: 'EOI signed',
  eoi_completed: 'EOI completed',
  email_received: 'New email',
  duplicate_alert: 'Possible duplicate',
  invoice_overdue: 'Invoice overdue',
  system_alert: 'System alert',
  follow_up_created: 'Follow-up',
  tenure_expiring: 'Tenure expiring',
  berth_released: 'Berth released',
};

function DigestBody({
  portName,
  recipientName,
  items,
  totalUnread,
  inboxLink,
  accent,
}: DigestData & { accent: string }) {
  const greeting = recipientName ? `Hi ${recipientName},` : 'Hi,';
  return (
    <>
      <Text style={{ fontSize: '18px', fontWeight: 'bold', color: accent, margin: '0 0 6px' }}>
        Your {portName} update
      </Text>
      <Text style={{ fontSize: '14px', lineHeight: '1.5', margin: '0 0 14px' }}>{greeting}</Text>
      <Text style={{ fontSize: '14px', lineHeight: '1.5', margin: '0 0 16px' }}>
        Here&apos;s what&apos;s waiting for you - <strong>{totalUnread}</strong> item
        {totalUnread === 1 ? '' : 's'} since your last digest.
      </Text>
      <table role="presentation" width="100%" cellSpacing={0} cellPadding={0} border={0}>
        <tbody>
          {items.map((item, i) => {
            const label = TYPE_LABELS[item.type] ?? item.type.replace(/_/g, ' ');
            return (
              <tr key={i}>
                <td style={{ padding: '10px 0', borderBottom: '1px solid #eee' }}>
                  <div
                    style={{
                      fontSize: '11px',
                      textTransform: 'uppercase',
                      color: '#999',
                      letterSpacing: '0.04em',
                    }}
                  >
                    {label}
                  </div>
                  <div style={{ fontSize: '14px', marginTop: '2px' }}>
                    {item.link ? (
                      <Link
                        href={safeUrl(item.link)}
                        style={{ color: accent, textDecoration: 'none' }}
                      >
                        <strong>{item.title}</strong>
                      </Link>
                    ) : (
                      <strong>{item.title}</strong>
                    )}
                  </div>
                  {item.description ? (
                    <div style={{ fontSize: '13px', color: '#666', marginTop: '4px' }}>
                      {item.description}
                    </div>
                  ) : null}
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
      {totalUnread > items.length ? (
        <Text style={{ marginTop: '14px', fontSize: '13px', color: '#666' }}>
          …and {totalUnread - items.length} more.{' '}
          <Link href={safeUrl(inboxLink)} style={{ color: accent }}>
            Open the inbox
          </Link>{' '}
          to see everything.
        </Text>
      ) : null}
      <Text style={{ marginTop: '24px', fontSize: '13px', color: '#666' }}>
        With warm regards,
        <br />
        <strong>The {portName} Team</strong>
      </Text>
    </>
  );
}

export async function notificationDigestEmail(
  data: DigestData,
  overrides?: RenderOpts,
): Promise<{ subject: string; html: string; text: string }> {
  const subject = overrides?.subject?.trim()
    ? overrides.subject
    : `Your ${data.portName} update - ${data.totalUnread} new item${data.totalUnread === 1 ? '' : 's'}`;
  const accent = brandingPrimaryColor(overrides?.branding);

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

  const text = [
    `Your ${data.portName} update`,
    '',
    `Here's what's waiting for you - ${data.totalUnread} item${data.totalUnread === 1 ? '' : 's'} since your last digest.`,
    '',
    ...data.items.map((i) => `• [${i.type.replace(/_/g, ' ')}] ${i.title}`),
    '',
    `Inbox: ${data.inboxLink}`,
    '',
    'With warm regards,',
    `The ${data.portName} Team`,
  ].join('\n');

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