// Rich HTML Email Templates for Report Delivery
// Provides professionally styled email templates for various report types

import type { ReportColumn } from './report-definitions';
import { BRAND } from '@/lib/white-label/constants';

// Additional type exports for API routes
export interface AlertEmailData {
  alertType: 'critical' | 'warning' | 'info';
  title: string;
  message: string;
  details?: string;
  actionUrl?: string;
  actionLabel?: string;
}

export interface ExecutiveBriefData {
  briefDate: Date;
  greeting?: string;
  highlights?: string[];
  marketIntel?: { title: string; content: string }[];
  operationsHealth?: { metric: string; value: string | number; status: 'good' | 'warning' | 'critical' }[];
  actionItems?: { priority: 'high' | 'medium' | 'low'; item: string }[];
  anomalies?: { description: string; severity: string }[];
}

export interface EmailContext {
  reportName: string;
  reportDescription?: string;
  recipientName?: string;
  generatedAt: Date;
  scheduleName?: string;
  periodLabel?: string;
  summaryMetrics?: SummaryMetric[];
  tableData?: { columns: ReportColumn[]; rows: Record<string, unknown>[] };
  chartImageUrl?: string;
  detailLink?: string;
  unsubscribeLink?: string;
}

export interface SummaryMetric {
  label: string;
  value: string | number;
  change?: number;
  changeLabel?: string;
  format?: 'number' | 'currency' | 'percentage';
  color?: 'cyan' | 'green' | 'red' | 'amber' | 'purple';
}

const BRAND_COLORS = {
  primary: '#0EA5E9', // cyan
  secondary: '#FDBA74', // purple
  success: '#10b981', // green
  warning: '#f59e0b', // amber
  danger: '#ef4444', // red
  background: '#0C1222',
  cardBackground: '#1e293b',
  text: '#e2e8f0',
  textMuted: '#94a3b8',
  border: '#334155',
};

const COLOR_MAP: Record<string, string> = {
  cyan: BRAND_COLORS.primary,
  green: BRAND_COLORS.success,
  red: BRAND_COLORS.danger,
  amber: BRAND_COLORS.warning,
  purple: BRAND_COLORS.secondary,
};

// Base email wrapper
function emailWrapper(content: string, context: EmailContext): string {
  return `
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>${context.reportName}</title>
  <style>
    body {
      margin: 0;
      padding: 0;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      background-color: ${BRAND_COLORS.background};
      color: ${BRAND_COLORS.text};
    }
    .container {
      max-width: 680px;
      margin: 0 auto;
      padding: 40px 20px;
    }
    .card {
      background-color: ${BRAND_COLORS.cardBackground};
      border-radius: 12px;
      padding: 32px;
      margin-bottom: 24px;
      border: 1px solid ${BRAND_COLORS.border};
    }
    .header {
      text-align: center;
      margin-bottom: 32px;
    }
    .logo {
      font-size: 28px;
      font-weight: bold;
      background: linear-gradient(135deg, ${BRAND_COLORS.primary}, ${BRAND_COLORS.secondary});
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }
    .report-title {
      font-size: 24px;
      font-weight: bold;
      color: ${BRAND_COLORS.text};
      margin: 16px 0 8px;
    }
    .report-subtitle {
      color: ${BRAND_COLORS.textMuted};
      font-size: 14px;
    }
    .metrics-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
      gap: 16px;
      margin: 24px 0;
    }
    .metric-card {
      background-color: rgba(15, 23, 42, 0.5);
      border-radius: 8px;
      padding: 16px;
      text-align: center;
      border: 1px solid ${BRAND_COLORS.border};
    }
    .metric-value {
      font-size: 28px;
      font-weight: bold;
      margin-bottom: 4px;
    }
    .metric-label {
      font-size: 12px;
      color: ${BRAND_COLORS.textMuted};
      text-transform: uppercase;
      letter-spacing: 0.5px;
    }
    .metric-change {
      font-size: 12px;
      margin-top: 4px;
    }
    .change-positive {
      color: ${BRAND_COLORS.success};
    }
    .change-negative {
      color: ${BRAND_COLORS.danger};
    }
    table {
      width: 100%;
      border-collapse: collapse;
      margin: 24px 0;
    }
    th {
      background-color: rgba(15, 23, 42, 0.5);
      padding: 12px 16px;
      text-align: left;
      font-size: 12px;
      font-weight: 600;
      text-transform: uppercase;
      letter-spacing: 0.5px;
      color: ${BRAND_COLORS.textMuted};
      border-bottom: 2px solid ${BRAND_COLORS.primary};
    }
    td {
      padding: 12px 16px;
      border-bottom: 1px solid ${BRAND_COLORS.border};
      font-size: 14px;
    }
    tr:hover {
      background-color: rgba(6, 182, 212, 0.05);
    }
    .btn {
      display: inline-block;
      padding: 12px 24px;
      background: linear-gradient(135deg, ${BRAND_COLORS.primary}, ${BRAND_COLORS.secondary});
      color: white;
      text-decoration: none;
      border-radius: 8px;
      font-weight: 600;
      margin: 16px 0;
    }
    .btn:hover {
      opacity: 0.9;
    }
    .footer {
      text-align: center;
      padding: 24px;
      color: ${BRAND_COLORS.textMuted};
      font-size: 12px;
    }
    .footer a {
      color: ${BRAND_COLORS.primary};
      text-decoration: none;
    }
    .divider {
      height: 1px;
      background: linear-gradient(to right, transparent, ${BRAND_COLORS.border}, transparent);
      margin: 24px 0;
    }
    .highlight-box {
      background: linear-gradient(135deg, rgba(6, 182, 212, 0.1), rgba(139, 92, 246, 0.1));
      border-left: 3px solid ${BRAND_COLORS.primary};
      padding: 16px;
      border-radius: 0 8px 8px 0;
      margin: 16px 0;
    }
    .chart-container {
      text-align: center;
      margin: 24px 0;
    }
    .chart-container img {
      max-width: 100%;
      border-radius: 8px;
    }
    @media only screen and (max-width: 480px) {
      .container {
        padding: 20px 10px;
      }
      .card {
        padding: 20px;
      }
      .metric-value {
        font-size: 22px;
      }
    }
  </style>
</head>
<body>
  <div class="container">
    ${content}
  </div>
</body>
</html>
`;
}

// Header section
function renderHeader(context: EmailContext): string {
  const dateStr = context.generatedAt.toLocaleDateString('en-US', {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  });

  return `
    <div class="header">
      <div class="logo">👻 ${BRAND.companyName}</div>
      <h1 class="report-title">${context.reportName}</h1>
      ${context.reportDescription ? `<p class="report-subtitle">${context.reportDescription}</p>` : ''}
      <p class="report-subtitle">
        ${context.periodLabel || dateStr}
        ${context.scheduleName ? ` • ${context.scheduleName}` : ''}
      </p>
    </div>
  `;
}

// Metrics section
function renderMetrics(metrics: SummaryMetric[]): string {
  if (!metrics || metrics.length === 0) return '';

  const metricCards = metrics
    .map((metric) => {
      const color = COLOR_MAP[metric.color || 'cyan'] || BRAND_COLORS.primary;
      let valueStr = String(metric.value);

      if (metric.format === 'currency') {
        valueStr = new Intl.NumberFormat('en-US', {
          style: 'currency',
          currency: 'USD',
          minimumFractionDigits: 0,
          maximumFractionDigits: 0,
        }).format(Number(metric.value));
      } else if (metric.format === 'percentage') {
        valueStr = `${metric.value}%`;
      } else if (metric.format === 'number') {
        valueStr = new Intl.NumberFormat('en-US').format(Number(metric.value));
      }

      let changeHtml = '';
      if (metric.change !== undefined) {
        const isPositive = metric.change >= 0;
        const changeClass = isPositive ? 'change-positive' : 'change-negative';
        const arrow = isPositive ? '↑' : '↓';
        changeHtml = `
          <div class="metric-change ${changeClass}">
            ${arrow} ${Math.abs(metric.change).toFixed(1)}% ${metric.changeLabel || 'vs prior'}
          </div>
        `;
      }

      return `
        <div class="metric-card">
          <div class="metric-value" style="color: ${color}">${valueStr}</div>
          <div class="metric-label">${metric.label}</div>
          ${changeHtml}
        </div>
      `;
    })
    .join('');

  return `<div class="metrics-grid">${metricCards}</div>`;
}

// Table section
function renderTable(columns: ReportColumn[], rows: Record<string, unknown>[], maxRows = 10): string {
  if (!columns || columns.length === 0 || !rows || rows.length === 0) return '';

  const displayRows = rows.slice(0, maxRows);
  const hasMore = rows.length > maxRows;

  const headerHtml = columns
    .map((col) => `<th>${col.label}</th>`)
    .join('');

  const rowsHtml = displayRows
    .map((row) => {
      const cells = columns
        .map((col) => {
          let value = row[col.key];
          if (col.format === 'currency' && typeof value === 'number') {
            value = new Intl.NumberFormat('en-US', {
              style: 'currency',
              currency: 'USD',
            }).format(value);
          } else if (col.format === 'percentage' && typeof value === 'number') {
            value = `${value.toFixed(1)}%`;
          } else if (col.format === 'date' && value) {
            value = new Date(String(value)).toLocaleDateString();
          }
          return `<td>${value ?? '-'}</td>`;
        })
        .join('');
      return `<tr>${cells}</tr>`;
    })
    .join('');

  return `
    <table>
      <thead>
        <tr>${headerHtml}</tr>
      </thead>
      <tbody>
        ${rowsHtml}
      </tbody>
    </table>
    ${hasMore ? `<p style="color: ${BRAND_COLORS.textMuted}; font-size: 12px; text-align: center;">Showing ${maxRows} of ${rows.length} rows. View full report for complete data.</p>` : ''}
  `;
}

// Call-to-action section
function renderCTA(detailLink?: string): string {
  if (!detailLink) return '';

  return `
    <div style="text-align: center;">
      <a href="${detailLink}" class="btn">View Full Report →</a>
    </div>
  `;
}

// Footer section
function renderFooter(unsubscribeLink?: string): string {
  return `
    <div class="footer">
      <p>Generated by $${BRAND.companyName} • Autonomous Operations Platform</p>
      <p>
        <a href="https://${BRAND.domain}">${BRAND.domain}</a>
        ${unsubscribeLink ? ` • <a href="${unsubscribeLink}">Manage subscriptions</a>` : ''}
      </p>
    </div>
  `;
}

// ============================================
// EMAIL TEMPLATES
// ============================================

// Standard Report Email
export function generateReportEmail(context: EmailContext): string {
  const content = `
    <div class="card">
      ${renderHeader(context)}
      <div class="divider"></div>
      ${context.summaryMetrics ? renderMetrics(context.summaryMetrics) : ''}
      ${context.chartImageUrl ? `<div class="chart-container"><img src="${context.chartImageUrl}" alt="Chart" /></div>` : ''}
      ${context.tableData ? renderTable(context.tableData.columns, context.tableData.rows) : ''}
      ${renderCTA(context.detailLink)}
    </div>
    ${renderFooter(context.unsubscribeLink)}
  `;

  return emailWrapper(content, context);
}

// Executive Summary Email
export function generateExecutiveSummaryEmail(context: EmailContext & { highlights?: string[]; alerts?: { severity: string; message: string }[] }): string {
  const highlightsHtml = context.highlights && context.highlights.length > 0
    ? `
      <div class="highlight-box">
        <h3 style="margin: 0 0 12px; font-size: 14px; color: ${BRAND_COLORS.text};">📊 Key Highlights</h3>
        <ul style="margin: 0; padding-left: 20px; color: ${BRAND_COLORS.textMuted};">
          ${context.highlights.map((h) => `<li style="margin-bottom: 8px;">${h}</li>`).join('')}
        </ul>
      </div>
    `
    : '';

  const alertsHtml = context.alerts && context.alerts.length > 0
    ? `
      <div style="margin: 24px 0;">
        <h3 style="font-size: 14px; color: ${BRAND_COLORS.text}; margin-bottom: 12px;">⚠️ Alerts & Actions</h3>
        ${context.alerts
          .map((alert) => {
            const bgColor = alert.severity === 'critical' ? 'rgba(239, 68, 68, 0.1)' : alert.severity === 'warning' ? 'rgba(245, 158, 11, 0.1)' : 'rgba(6, 182, 212, 0.1)';
            const borderColor = alert.severity === 'critical' ? BRAND_COLORS.danger : alert.severity === 'warning' ? BRAND_COLORS.warning : BRAND_COLORS.primary;
            return `
              <div style="background: ${bgColor}; border-left: 3px solid ${borderColor}; padding: 12px 16px; border-radius: 0 8px 8px 0; margin-bottom: 8px;">
                <p style="margin: 0; font-size: 14px;">${alert.message}</p>
              </div>
            `;
          })
          .join('')}
      </div>
    `
    : '';

  const content = `
    <div class="card">
      ${renderHeader(context)}
      <div class="divider"></div>
      ${highlightsHtml}
      ${context.summaryMetrics ? renderMetrics(context.summaryMetrics) : ''}
      ${alertsHtml}
      ${context.tableData ? renderTable(context.tableData.columns, context.tableData.rows, 5) : ''}
      ${renderCTA(context.detailLink)}
    </div>
    ${renderFooter(context.unsubscribeLink)}
  `;

  return emailWrapper(content, context);
}

// Alert/Notification Email
export function generateAlertEmail(context: EmailContext & { alertType: 'critical' | 'warning' | 'info'; alertMessage: string; actionRequired?: string }): string {
  const colors = {
    critical: { bg: 'rgba(239, 68, 68, 0.1)', border: BRAND_COLORS.danger, icon: '🚨' },
    warning: { bg: 'rgba(245, 158, 11, 0.1)', border: BRAND_COLORS.warning, icon: '⚠️' },
    info: { bg: 'rgba(6, 182, 212, 0.1)', border: BRAND_COLORS.primary, icon: 'ℹ️' },
  };
  const alertStyle = colors[context.alertType];

  const content = `
    <div class="card">
      <div class="header">
        <div class="logo">👻 ${BRAND.companyName}</div>
        <h1 class="report-title">${alertStyle.icon} ${context.reportName}</h1>
      </div>
      <div class="divider"></div>
      <div style="background: ${alertStyle.bg}; border-left: 4px solid ${alertStyle.border}; padding: 20px; border-radius: 0 12px 12px 0; margin: 24px 0;">
        <p style="margin: 0; font-size: 16px; line-height: 1.6;">${context.alertMessage}</p>
      </div>
      ${context.actionRequired ? `
        <div class="highlight-box">
          <h3 style="margin: 0 0 8px; font-size: 14px;">📋 Action Required</h3>
          <p style="margin: 0; color: ${BRAND_COLORS.textMuted};">${context.actionRequired}</p>
        </div>
      ` : ''}
      ${context.summaryMetrics ? renderMetrics(context.summaryMetrics) : ''}
      ${renderCTA(context.detailLink)}
    </div>
    ${renderFooter(context.unsubscribeLink)}
  `;

  return emailWrapper(content, context);
}

// Schedule Confirmation Email
export function generateScheduleConfirmationEmail(context: EmailContext & { frequency: string; nextRunAt: Date }): string {
  const nextRunStr = context.nextRunAt.toLocaleDateString('en-US', {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });

  const content = `
    <div class="card">
      <div class="header">
        <div class="logo">👻 ${BRAND.companyName}</div>
        <h1 class="report-title">✅ Report Scheduled</h1>
        <p class="report-subtitle">Your report subscription has been confirmed</p>
      </div>
      <div class="divider"></div>
      <div class="highlight-box">
        <h3 style="margin: 0 0 16px; font-size: 14px;">📋 Subscription Details</h3>
        <table style="margin: 0;">
          <tr>
            <td style="padding: 8px 0; color: ${BRAND_COLORS.textMuted}; border: none;">Report:</td>
            <td style="padding: 8px 0; padding-left: 16px; border: none;">${context.reportName}</td>
          </tr>
          <tr>
            <td style="padding: 8px 0; color: ${BRAND_COLORS.textMuted}; border: none;">Frequency:</td>
            <td style="padding: 8px 0; padding-left: 16px; border: none; text-transform: capitalize;">${context.frequency}</td>
          </tr>
          <tr>
            <td style="padding: 8px 0; color: ${BRAND_COLORS.textMuted}; border: none;">Next Delivery:</td>
            <td style="padding: 8px 0; padding-left: 16px; border: none;">${nextRunStr}</td>
          </tr>
        </table>
      </div>
      <p style="color: ${BRAND_COLORS.textMuted}; font-size: 14px; text-align: center;">
        You'll receive this report automatically at your scheduled time.
      </p>
      ${renderCTA(context.detailLink)}
    </div>
    ${renderFooter(context.unsubscribeLink)}
  `;

  return emailWrapper(content, context);
}

// Digest Email (multiple reports summary)
export function generateDigestEmail(context: EmailContext & { reports: { name: string; summary: string; link: string }[] }): string {
  const reportsHtml = context.reports
    .map(
      (report) => `
      <div style="background: rgba(15, 23, 42, 0.5); border-radius: 8px; padding: 16px; margin-bottom: 12px; border: 1px solid ${BRAND_COLORS.border};">
        <h4 style="margin: 0 0 8px; font-size: 16px; color: ${BRAND_COLORS.text};">${report.name}</h4>
        <p style="margin: 0 0 12px; font-size: 14px; color: ${BRAND_COLORS.textMuted};">${report.summary}</p>
        <a href="${report.link}" style="font-size: 14px; color: ${BRAND_COLORS.primary}; text-decoration: none;">View Report →</a>
      </div>
    `
    )
    .join('');

  const content = `
    <div class="card">
      ${renderHeader(context)}
      <div class="divider"></div>
      <h3 style="font-size: 14px; color: ${BRAND_COLORS.textMuted}; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 16px;">
        📊 Reports Summary
      </h3>
      ${reportsHtml}
    </div>
    ${renderFooter(context.unsubscribeLink)}
  `;

  return emailWrapper(content, context);
}
