import puppeteer from 'puppeteer';

export interface PDFReportData {
  projectTitle: string;
  overallScore: number;
  totalPossible: number;
  grade: string;
  analysisDate: string;
  criteria: Array<{
    name: string;
    score: number;
    maxScore: number;
    weight: number;
    weightedScore: number;
    percentage: number;
    feedback: string;
    strengths: string[];
    improvements: string[];
  }>;
  overview: {
    excellentItems: number;
    improvementItems: number;
    overallPerformance: number;
  };
  improvementSuggestions: {
    overallSuggestions: string;
    maintainStrengths: Array<{
      title: string;
      description: string;
    }>;
    keyImprovements: Array<{
      title: string;
      subtitle?: string;
      description?: string;
      suggestions: string[];
    }>;
    actionPlan: Array<{
      phase: string;
      description: string;
    }>;
  };
}

export class HTMLPDFGenerator {
  private generateHTML(data: PDFReportData): string {
    return `
<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI 智能評審報告</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft JhengHei', 'PingFang TC', 'Helvetica Neue', Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            background: white;
            padding: 20px;
        }
        
        .header {
            text-align: center;
            margin-bottom: 30px;
            border-bottom: 2px solid #0891b2;
            padding-bottom: 20px;
        }
        
        .title {
            font-size: 28px;
            font-weight: bold;
            color: #0891b2;
            margin-bottom: 10px;
        }
        
        .subtitle {
            font-size: 16px;
            color: #666;
        }
        
        .section {
            margin-bottom: 25px;
        }
        
        .section-title {
            font-size: 18px;
            font-weight: bold;
            color: #0891b2;
            margin-bottom: 15px;
            border-left: 4px solid #0891b2;
            padding-left: 10px;
        }
        
        .score-box {
            background: #f8f9fa;
            border: 2px solid #0891b2;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            margin: 20px 0;
            display: inline-block;
            min-width: 200px;
        }
        
        .score-number {
            font-size: 36px;
            font-weight: bold;
            color: #0891b2;
        }
        
        .score-grade {
            font-size: 20px;
            font-weight: bold;
            color: #10b981;
            margin-top: 5px;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 20px;
            margin: 20px 0;
        }
        
        .stat-card {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            text-align: center;
        }
        
        .stat-number {
            font-size: 24px;
            font-weight: bold;
            color: #0891b2;
        }
        
        .stat-label {
            font-size: 14px;
            color: #666;
            margin-top: 5px;
        }
        
        .criteria-table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }
        
        .criteria-table th,
        .criteria-table td {
            border: 1px solid #ddd;
            padding: 12px;
            text-align: left;
        }
        
        .criteria-table th {
            background: #0891b2;
            color: white;
            font-weight: bold;
        }
        
        .criteria-table tr:nth-child(even) {
            background: #f8f9fa;
        }
        
        .criteria-item {
            background: white;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            padding: 20px;
            margin: 15px 0;
        }
        
        .criteria-name {
            font-size: 16px;
            font-weight: bold;
            color: #0891b2;
            margin-bottom: 10px;
        }
        
        .criteria-score {
            font-size: 18px;
            font-weight: bold;
            color: #10b981;
            margin-bottom: 10px;
        }
        
        .criteria-feedback {
            margin: 10px 0;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 4px;
        }
        
        .strengths, .improvements {
            margin: 10px 0;
        }
        
        .strengths h4, .improvements h4 {
            color: #10b981;
            margin-bottom: 8px;
        }
        
        .improvements h4 {
            color: #f59e0b;
        }
        
        .strengths ul, .improvements ul {
            margin-left: 20px;
        }
        
        .strengths li, .improvements li {
            margin: 5px 0;
        }
        
        .suggestions-section {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin: 20px 0;
        }
        
        .suggestion-group {
            margin: 15px 0;
        }
        
        .suggestion-title {
            font-weight: bold;
            color: #0891b2;
            margin-bottom: 8px;
        }
        
        .suggestion-description {
            margin: 8px 0;
        }
        
        .suggestion-list {
            margin-left: 20px;
        }
        
        .action-plan {
            background: #e0f2fe;
            border-radius: 8px;
            padding: 20px;
            margin: 20px 0;
        }
        
        .action-item {
            display: flex;
            align-items: flex-start;
            margin: 10px 0;
        }
        
        .action-number {
            background: #0891b2;
            color: white;
            width: 24px;
            height: 24px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-right: 12px;
            flex-shrink: 0;
        }
        
        .action-content {
            flex: 1;
        }
        
        .action-phase {
            font-weight: bold;
            color: #0891b2;
            margin-bottom: 4px;
        }
        
        .footer {
            margin-top: 40px;
            padding-top: 20px;
            border-top: 1px solid #e5e7eb;
            text-align: center;
            color: #666;
            font-size: 12px;
        }
        
        @media print {
            body {
                padding: 0;
            }
            
            .page-break {
                page-break-before: always;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <h1 class="title">AI 智能評審報告</h1>
        <p class="subtitle">專案名稱：${data.projectTitle}</p>
        <p class="subtitle">分析日期：${data.analysisDate}</p>
    </div>

    <div class="section">
        <h2 class="section-title">總評結果</h2>
        <div class="score-box">
            <div class="score-number">${data.overallScore}/${data.totalPossible}</div>
            <div class="score-grade">${data.grade}</div>
        </div>
    </div>

    <div class="section">
        <h2 class="section-title">統計概覽</h2>
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-number">${data.overview.excellentItems}</div>
                <div class="stat-label">優秀項目</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">${data.overview.improvementItems}</div>
                <div class="stat-label">待改進項目</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">${data.overview.overallPerformance}%</div>
                <div class="stat-label">整體表現</div>
            </div>
        </div>
    </div>

    <div class="section">
        <h2 class="section-title">評分明細</h2>
        <table class="criteria-table">
            <thead>
                <tr>
                    <th>評分項目</th>
                    <th>得分</th>
                    <th>權重</th>
                    <th>加權分</th>
                </tr>
            </thead>
            <tbody>
                ${data.criteria.map(item => `
                    <tr>
                        <td>${item.name}</td>
                        <td>${item.score}/${item.maxScore}</td>
                        <td>${item.weight}%</td>
                        <td>${item.weightedScore.toFixed(1)}</td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    </div>

    <div class="section page-break">
        <h2 class="section-title">詳細分析</h2>
        ${data.criteria.map(item => `
            <div class="criteria-item">
                <div class="criteria-name">${item.name}</div>
                <div class="criteria-score">得分：${item.score}/${item.maxScore} (${item.percentage.toFixed(1)}%)</div>
                <div class="criteria-feedback">
                    <strong>AI 評語：</strong>${item.feedback}
                </div>
                ${item.strengths.length > 0 ? `
                    <div class="strengths">
                        <h4>優點：</h4>
                        <ul>
                            ${item.strengths.map(strength => `<li>${strength}</li>`).join('')}
                        </ul>
                    </div>
                ` : ''}
                ${item.improvements.length > 0 ? `
                    <div class="improvements">
                        <h4>改進建議：</h4>
                        <ul>
                            ${item.improvements.map(improvement => `<li>${improvement}</li>`).join('')}
                        </ul>
                    </div>
                ` : ''}
            </div>
        `).join('')}
    </div>

    <div class="section page-break">
        <h2 class="section-title">整體改進建議</h2>
        <div class="suggestions-section">
            <p>${data.improvementSuggestions.overallSuggestions}</p>
        </div>
    </div>

    ${data.improvementSuggestions.maintainStrengths.length > 0 ? `
        <div class="section">
            <h2 class="section-title">繼續保持的優勢</h2>
            <div class="suggestions-section">
                ${data.improvementSuggestions.maintainStrengths.map(strength => `
                    <div class="suggestion-group">
                        <div class="suggestion-title">${strength.title}</div>
                        <div class="suggestion-description">${strength.description}</div>
                    </div>
                `).join('')}
            </div>
        </div>
    ` : ''}

    ${data.improvementSuggestions.keyImprovements.length > 0 ? `
        <div class="section page-break">
            <h2 class="section-title">重點改進方向</h2>
            <div class="suggestions-section">
                ${data.improvementSuggestions.keyImprovements.map(improvement => `
                    <div class="suggestion-group">
                        <div class="suggestion-title">${improvement.title}</div>
                        ${improvement.description ? `<div class="suggestion-description">${improvement.description}</div>` : ''}
                        ${improvement.suggestions.length > 0 ? `
                            <div class="suggestion-list">
                                <ul>
                                    ${improvement.suggestions.map(suggestion => `<li>${suggestion}</li>`).join('')}
                                </ul>
                            </div>
                        ` : ''}
                    </div>
                `).join('')}
            </div>
        </div>
    ` : ''}

    ${data.improvementSuggestions.actionPlan.length > 0 ? `
        <div class="section">
            <h2 class="section-title">下一步行動計劃</h2>
            <div class="action-plan">
                ${data.improvementSuggestions.actionPlan.map((action, index) => `
                    <div class="action-item">
                        <div class="action-number">${index + 1}</div>
                        <div class="action-content">
                            <div class="action-phase">${action.phase}</div>
                            <div>${action.description}</div>
                        </div>
                    </div>
                `).join('')}
            </div>
        </div>
    ` : ''}

    <div class="footer">
        <p>本報告由 AI 智能評審系統生成</p>
        <p>生成時間：${new Date().toLocaleString('zh-TW')}</p>
    </div>
</body>
</html>
    `;
  }

  public async generateReport(data: PDFReportData): Promise<Blob> {
    const browser = await puppeteer.launch({
      headless: true,
      args: [
        '--no-sandbox',
        '--disable-setuid-sandbox',
        '--disable-dev-shm-usage',
        '--disable-accelerated-2d-canvas',
        '--no-first-run',
        '--no-zygote',
        '--disable-gpu'
      ],
      timeout: 30000
    });

    try {
      const page = await browser.newPage();
      
      // 設置頁面內容
      const html = this.generateHTML(data);
      await page.setContent(html, { waitUntil: 'networkidle0' });

      // 生成 PDF
      const pdfBuffer = await page.pdf({
        format: 'A4',
        printBackground: true,
        margin: {
          top: '20mm',
          right: '20mm',
          bottom: '20mm',
          left: '20mm'
        }
      });

      return new Blob([pdfBuffer], { type: 'application/pdf' });
    } finally {
      await browser.close();
    }
  }
}

// 便捷函數
export async function generateHTMLPDFReport(data: PDFReportData): Promise<Blob> {
  const generator = new HTMLPDFGenerator();
  return generator.generateReport(data);
}
