import { writeFileSync, mkdirSync, copyFileSync } from 'fs';
import { join, dirname } from 'path';
import Handlebars from 'handlebars';
import type { CoverageReport } from '../types';

export class HtmlReporter {
  private template: HandlebarsTemplateDelegate;

  constructor() {
    this.registerHelpers();
    this.template = this.compileTemplate();
  }

  report(coverage: CoverageReport, outputDir: string): void {
    const htmlDir = join(outputDir, 'html');
    mkdirSync(htmlDir, { recursive: true });

    // Generate main report
    const html = this.template({
      coverage,
      timestamp: new Date(coverage.timestamp).toLocaleString(),
      thresholds: coverage.config.thresholds,
    });

    writeFileSync(join(htmlDir, 'index.html'), html);
    
    // Write CSS
    this.writeStyles(htmlDir);
    
    console.log(`HTML coverage report written to: ${join(htmlDir, 'index.html')}`);
  }

  private registerHelpers(): void {
    Handlebars.registerHelper('percentage', (value: number) => value.toFixed(1));
    
    Handlebars.registerHelper('coverageClass', (percentage: number, threshold?: number) => {
      if (!threshold) return 'neutral';
      if (percentage >= threshold) return 'good';
      if (percentage >= threshold * 0.9) return 'warning';
      return 'bad';
    });
    
    Handlebars.registerHelper('coverageIcon', (percentage: number, threshold?: number) => {
      if (!threshold) return '';
      if (percentage >= threshold) return '✓';
      if (percentage >= threshold * 0.9) return '⚠';
      return '✗';
    });

    Handlebars.registerHelper('shortenPath', (path: string) => {
      const parts = path.split('/');
      if (parts.length > 4) {
        return '.../' + parts.slice(-3).join('/');
      }
      return path;
    });
  }

  private compileTemplate(): HandlebarsTemplateDelegate {
    const template = `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stock Bot Coverage Report</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <header>
            <h1>Stock Bot Coverage Report</h1>
            <p class="timestamp">Generated: {{timestamp}}</p>
        </header>

        <section class="summary">
            <h2>Overall Coverage</h2>
            <div class="metrics">
                <div class="metric {{coverageClass coverage.overall.lines.percentage thresholds.lines}}">
                    <div class="metric-name">Lines</div>
                    <div class="metric-value">
                        {{percentage coverage.overall.lines.percentage}}%
                        <span class="icon">{{coverageIcon coverage.overall.lines.percentage thresholds.lines}}</span>
                    </div>
                    <div class="metric-detail">
                        {{coverage.overall.lines.covered}} / {{coverage.overall.lines.total}}
                    </div>
                </div>
                
                <div class="metric {{coverageClass coverage.overall.functions.percentage thresholds.functions}}">
                    <div class="metric-name">Functions</div>
                    <div class="metric-value">
                        {{percentage coverage.overall.functions.percentage}}%
                        <span class="icon">{{coverageIcon coverage.overall.functions.percentage thresholds.functions}}</span>
                    </div>
                    <div class="metric-detail">
                        {{coverage.overall.functions.covered}} / {{coverage.overall.functions.total}}
                    </div>
                </div>
                
                <div class="metric {{coverageClass coverage.overall.branches.percentage thresholds.branches}}">
                    <div class="metric-name">Branches</div>
                    <div class="metric-value">
                        {{percentage coverage.overall.branches.percentage}}%
                        <span class="icon">{{coverageIcon coverage.overall.branches.percentage thresholds.branches}}</span>
                    </div>
                    <div class="metric-detail">
                        {{coverage.overall.branches.covered}} / {{coverage.overall.branches.total}}
                    </div>
                </div>
                
                <div class="metric {{coverageClass coverage.overall.statements.percentage thresholds.statements}}">
                    <div class="metric-name">Statements</div>
                    <div class="metric-value">
                        {{percentage coverage.overall.statements.percentage}}%
                        <span class="icon">{{coverageIcon coverage.overall.statements.percentage thresholds.statements}}</span>
                    </div>
                    <div class="metric-detail">
                        {{coverage.overall.statements.covered}} / {{coverage.overall.statements.total}}
                    </div>
                </div>
            </div>
        </section>

        <section class="packages">
            <h2>Package Coverage</h2>
            <table>
                <thead>
                    <tr>
                        <th>Package</th>
                        <th>Lines</th>
                        <th>Functions</th>
                        <th>Branches</th>
                        <th>Statements</th>
                    </tr>
                </thead>
                <tbody>
                    {{#each coverage.packages}}
                    <tr>
                        <td class="package-name">{{name}}</td>
                        <td class="{{coverageClass lines.percentage ../thresholds.lines}}">
                            {{percentage lines.percentage}}%
                        </td>
                        <td class="{{coverageClass functions.percentage ../thresholds.functions}}">
                            {{percentage functions.percentage}}%
                        </td>
                        <td class="{{coverageClass branches.percentage ../thresholds.branches}}">
                            {{percentage branches.percentage}}%
                        </td>
                        <td class="{{coverageClass statements.percentage ../thresholds.statements}}">
                            {{percentage statements.percentage}}%
                        </td>
                    </tr>
                    {{/each}}
                </tbody>
            </table>
        </section>

        {{#each coverage.packages}}
        <section class="package-details">
            <h3>{{name}}</h3>
            <div class="file-list">
                <table>
                    <thead>
                        <tr>
                            <th>File</th>
                            <th>Lines</th>
                            <th>Functions</th>
                            <th>Branches</th>
                            <th>Statements</th>
                        </tr>
                    </thead>
                    <tbody>
                        {{#each files}}
                        <tr>
                            <td class="file-path">{{shortenPath path}}</td>
                            <td class="{{coverageClass lines.percentage}}">
                                {{percentage lines.percentage}}%
                            </td>
                            <td class="{{coverageClass functions.percentage}}">
                                {{percentage functions.percentage}}%
                            </td>
                            <td class="{{coverageClass branches.percentage}}">
                                {{percentage branches.percentage}}%
                            </td>
                            <td class="{{coverageClass statements.percentage}}">
                                {{percentage statements.percentage}}%
                            </td>
                        </tr>
                        {{/each}}
                    </tbody>
                </table>
            </div>
        </section>
        {{/each}}
    </div>
</body>
</html>
    `;

    return Handlebars.compile(template);
  }

  private writeStyles(htmlDir: string): void {
    const css = `
:root {
    --color-good: #4caf50;
    --color-warning: #ff9800;
    --color-bad: #f44336;
    --color-neutral: #9e9e9e;
    --bg-primary: #f5f5f5;
    --bg-secondary: #ffffff;
    --text-primary: #212121;
    --text-secondary: #757575;
    --border-color: #e0e0e0;
}

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
    background-color: var(--bg-primary);
    color: var(--text-primary);
    line-height: 1.6;
}

.container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 2rem;
}

header {
    text-align: center;
    margin-bottom: 3rem;
}

h1 {
    font-size: 2.5rem;
    margin-bottom: 0.5rem;
}

.timestamp {
    color: var(--text-secondary);
}

.summary {
    background: var(--bg-secondary);
    border-radius: 8px;
    padding: 2rem;
    margin-bottom: 2rem;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.metrics {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1.5rem;
    margin-top: 1.5rem;
}

.metric {
    text-align: center;
    padding: 1.5rem;
    border-radius: 8px;
    background: var(--bg-primary);
}

.metric.good {
    border: 2px solid var(--color-good);
}

.metric.warning {
    border: 2px solid var(--color-warning);
}

.metric.bad {
    border: 2px solid var(--color-bad);
}

.metric.neutral {
    border: 2px solid var(--color-neutral);
}

.metric-name {
    font-size: 0.875rem;
    color: var(--text-secondary);
    text-transform: uppercase;
    letter-spacing: 0.05em;
}

.metric-value {
    font-size: 2rem;
    font-weight: bold;
    margin: 0.5rem 0;
}

.metric-detail {
    font-size: 0.875rem;
    color: var(--text-secondary);
}

.icon {
    margin-left: 0.5rem;
}

.packages {
    background: var(--bg-secondary);
    border-radius: 8px;
    padding: 2rem;
    margin-bottom: 2rem;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 1rem;
}

th, td {
    padding: 0.75rem;
    text-align: left;
    border-bottom: 1px solid var(--border-color);
}

th {
    font-weight: 600;
    color: var(--text-secondary);
    text-transform: uppercase;
    font-size: 0.875rem;
}

.package-name {
    font-weight: 500;
}

.good {
    color: var(--color-good);
    font-weight: 500;
}

.warning {
    color: var(--color-warning);
    font-weight: 500;
}

.bad {
    color: var(--color-bad);
    font-weight: 500;
}

.neutral {
    color: var(--color-neutral);
}

.package-details {
    background: var(--bg-secondary);
    border-radius: 8px;
    padding: 2rem;
    margin-bottom: 2rem;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.package-details h3 {
    margin-bottom: 1rem;
}

.file-path {
    font-family: 'Courier New', Courier, monospace;
    font-size: 0.875rem;
}

.file-list {
    max-height: 400px;
    overflow-y: auto;
}

@media (max-width: 768px) {
    .container {
        padding: 1rem;
    }
    
    .metrics {
        grid-template-columns: 1fr;
    }
    
    table {
        font-size: 0.875rem;
    }
    
    th, td {
        padding: 0.5rem;
    }
}
    `;

    writeFileSync(join(htmlDir, 'styles.css'), css);
  }
}