import * as fs from 'fs';
import * as path from 'path';
import { compile } from 'handlebars';
import { ReportDataPayload } from '@shieldai/types';

interface RenderContext {
  reportTitle: string;
  reportType: string;
  periodStart: string;
  periodEnd: string;
  generatedAt: string;
  userName: string;
  data: ReportDataPayload;
  dashboardUrl: string;
}

const BASE_TEMPLATE = `
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>{{reportTitle}}</title>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f7fa; color: #1a202c; line-height: 1.6; }
    .container { max-width: 640px; margin: 0 auto; padding: 20px; }
    .header { background: linear-gradient(135deg, #2563eb, #1d4ed8); color: white; padding: 32px 24px; border-radius: 12px 12px 0 0; text-align: center; }
    .header h1 { font-size: 24px; margin-bottom: 8px; }
    .header p { opacity: 0.9; font-size: 14px; }
    .section { background: white; margin: 16px 0; padding: 24px; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
    .section h2 { font-size: 18px; color: #1e40af; margin-bottom: 16px; padding-bottom: 8px; border-bottom: 2px solid #e2e8f0; }
    .stat-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px; }
    .stat-card { background: #f8fafc; padding: 16px; border-radius: 8px; text-align: center; }
    .stat-value { font-size: 28px; font-weight: 700; color: #2563eb; }
    .stat-label { font-size: 12px; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; margin-top: 4px; }
    .score-ring { width: 120px; height: 120px; border-radius: 50%; margin: 0 auto 16px; display: flex; align-items: center; justify-content: center; flex-direction: column; }
    .score-ring.high { background: linear-gradient(135deg, #22c55e, #16a34a); color: white; }
    .score-ring.medium { background: linear-gradient(135deg, #eab308, #ca8a04); color: white; }
    .score-ring.low { background: linear-gradient(135deg, #ef4444, #dc2626); color: white; }
    .score-number { font-size: 36px; font-weight: 700; }
    .score-label { font-size: 12px; opacity: 0.9; }
    .recommendation { padding: 12px 16px; margin: 8px 0; border-radius: 6px; border-left: 4px solid; }
    .recommendation.high { background: #fef2f2; border-color: #ef4444; }
    .recommendation.medium { background: #fffbeb; border-color: #eab308; }
    .recommendation.low { background: #f0fdf4; border-color: #22c55e; }
    .recommendation h3 { font-size: 14px; margin-bottom: 4px; }
    .recommendation p { font-size: 13px; color: #475569; }
    .footer { text-align: center; padding: 24px; color: #94a3b8; font-size: 12px; }
    .footer a { color: #2563eb; text-decoration: none; }
    .severity-critical { color: #ef4444; font-weight: 600; }
    .severity-warning { color: #eab308; font-weight: 600; }
    .severity-info { color: #2563eb; font-weight: 600; }
    table { width: 100%; border-collapse: collapse; margin-top: 12px; }
    th, td { padding: 8px 12px; text-align: left; border-bottom: 1px solid #e2e8f0; font-size: 13px; }
    th { background: #f8fafc; font-weight: 600; color: #475569; }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h1>{{reportTitle}}</h1>
      <p>{{periodStart}} &mdash; {{periodEnd}}</p>
      <p>Generated {{generatedAt}}</p>
    </div>

    <div class="section">
      <h2>Protection Score</h2>
      <div class="score-ring {{scoreClass}}">
        <span class="score-number">{{data.protectionScore}}</span>
        <span class="score-label">/ 100</span>
      </div>
      {{#if data.previousProtectionScore}}
      <p style="text-align:center; font-size:14px; color:#64748b;">
        Previous period: {{data.previousProtectionScore}}/100
        {{#if scoreImproved}}&nbsp;&nbsp;📈 Improved{{else}}&nbsp;&nbsp;📉 Declined{{/if}}
      </p>
      {{/if}}
    </div>

    <div class="section">
      <h2>Dark Web Exposure Summary</h2>
      <div class="stat-grid">
        <div class="stat-card">
          <div class="stat-value severity-critical">{{data.exposureSummary.criticalExposures}}</div>
          <div class="stat-label">Critical</div>
        </div>
        <div class="stat-card">
          <div class="stat-value severity-warning">{{data.exposureSummary.warningExposures}}</div>
          <div class="stat-label">Warnings</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{data.exposureSummary.newExposures}}</div>
          <div class="stat-label">New Findings</div>
        </div>
        <div class="stat-card">
          <div class="stat-value" style="color:#22c55e">{{data.exposureSummary.resolvedExposures}}</div>
          <div class="stat-label">Resolved</div>
        </div>
      </div>
      {{#if exposureSources}}
      <table>
        <tr><th>Source</th><th>Exposures</th></tr>
        {{#exposureSources}}
        <tr><td>{{key}}</td><td>{{value}}</td></tr>
        {{/exposureSources}}
      </table>
      {{/if}}
    </div>

    <div class="section">
      <h2>Spam Protection</h2>
      <div class="stat-grid">
        <div class="stat-card">
          <div class="stat-value">{{data.spamStats.callsBlocked}}</div>
          <div class="stat-label">Calls Blocked</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{data.spamStats.textsBlocked}}</div>
          <div class="stat-label">Texts Blocked</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{data.spamStats.totalSpamEvents}}</div>
          <div class="stat-label">Total Events</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{data.spamStats.falsePositives}}</div>
          <div class="stat-label">False Positives</div>
        </div>
      </div>
    </div>

    <div class="section">
      <h2>Voice Protection</h2>
      <div class="stat-grid">
        <div class="stat-card">
          <div class="stat-value">{{data.voiceStats.analysesRun}}</div>
          <div class="stat-label">Analyses Run</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{data.voiceStats.threatsDetected}}</div>
          <div class="stat-label">Threats Detected</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{data.voiceStats.enrollmentsActive}}</div>
          <div class="stat-label">Active Enrollments</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{data.voiceStats.syntheticDetections}}</div>
          <div class="stat-label">Synthetic Voices</div>
        </div>
      </div>
    </div>

    {{#if data.homeTitleStats}}
    <div class="section">
      <h2>Home Title Monitoring</h2>
      <div class="stat-grid">
        <div class="stat-card">
          <div class="stat-value">{{data.homeTitleStats.propertiesMonitored}}</div>
          <div class="stat-label">Properties Monitored</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{data.homeTitleStats.changesDetected}}</div>
          <div class="stat-label">Changes Detected</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{data.homeTitleStats.alertsTriggered}}</div>
          <div class="stat-label">Alerts Triggered</div>
        </div>
      </div>
    </div>
    {{/if}}

    {{#if data.recommendations}}
    <div class="section">
      <h2>Recommendations</h2>
      {{#data.recommendations}}
      <div class="recommendation {{priority}}">
        <h3>{{title}}</h3>
        <p>{{description}}</p>
      </div>
      {{/data.recommendations}}
    </div>
    {{/if}}

    <div class="footer">
      <p>ShieldAI &mdash; Your Digital Identity Protection</p>
      <p><a href="{{dashboardUrl}}">View Full Report Dashboard</a></p>
      <p>Report ID: {{reportId}}</p>
    </div>
  </div>
</body>
</html>
`;

export class HtmlRenderer {
  private template: ReturnType<typeof compile>;

  constructor() {
    this.template = compile(BASE_TEMPLATE);
  }

  render(context: RenderContext & { reportId: string }): string {
    const score = context.data.protectionScore;
    const scoreClass = score >= 70 ? 'high' : score >= 40 ? 'medium' : 'low';

    const exposureSources = Object.entries(context.data.exposureSummary.exposuresBySource)
      .map(([key, value]) => ({ key, value }));

    const periodStart = new Date(context.periodStart).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });

    const periodEnd = new Date(context.periodEnd).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });

    const generatedAt = new Date(context.generatedAt).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });

    const scoreImproved =
      context.data.previousProtectionScore !== undefined &&
      score > context.data.previousProtectionScore;

    return this.template({
      ...context,
      periodStart,
      periodEnd,
      generatedAt,
      scoreClass,
      scoreImproved,
      exposureSources,
    });
  }
}

export const htmlRenderer = new HtmlRenderer();
