import { Injectable, Logger } from '@nestjs/common';
import { MailsService } from '../mails/mails.service';
import { ReportData } from './report.service';

@Injectable()
export class MailerService {
  private readonly logger = new Logger(MailerService.name);

  constructor(private readonly mails: MailsService) {}

  /**
   * Sends the report (Excel + PDF) through your existing dynamic mail system.
   * `to` overrides the recipient (typed in the UI); falls back to MANAGEMENT_EMAIL.
   */
  async sendReport(
    report: ReportData,
    summary: string,
    excel: Buffer,
    pdf: Buffer,
    senderUserId: number,
    to?: string,
  ): Promise<void> {
    const recipient = (to && to.trim()) || process.env.MANAGEMENT_EMAIL || '';
    const base = `Certification_Report_${report.monthName}_${report.year}`;

    if (!recipient) {
      this.logger.warn('No recipient (to / MANAGEMENT_EMAIL) — skipping send.');
      return;
    }

    await this.mails.sendAsUser(senderUserId, {
      to: recipient,
      subject: `Certification Report — ${report.monthName} ${report.year} (${report.total} due)`,
      html: this.buildHtml(report, summary),
      attachments: [
        { filename: `${base}.xlsx`, content: excel },
        { filename: `${base}.pdf`, content: pdf },
      ],
    });

    this.logger.log(`Report emailed to ${recipient} from user #${senderUserId}: ${base}`);
  }

  /** Professional, brand-styled HTML email. */
  private buildHtml(report: ReportData, summary: string): string {
    const accents: Record<string, string> = {
      recert: '#D85A30',
      surv_11: '#1D9E75',
      surv_1: '#BA7517',
    };

    const cards = report.buckets
      .map(
        (b) => `
        <td width="33%" style="padding:6px;">
          <div style="background:#f8f5ff;border:1px solid #ede8ff;border-top:3px solid ${accents[b.key] ?? '#8b14d4'};border-radius:10px;padding:14px 12px;text-align:center;">
            <div style="font-size:26px;font-weight:700;color:#1a0440;line-height:1;">${b.count}</div>
            <div style="font-size:11px;color:#6b7280;margin-top:6px;text-transform:uppercase;letter-spacing:.4px;">${b.label}</div>
          </div>
        </td>`,
      )
      .join('');

    return `
    <div style="background:#eef1f5;padding:28px 12px;font-family:'Segoe UI',Arial,Helvetica,sans-serif;">
      <table role="presentation" width="600" cellpadding="0" cellspacing="0" align="center" style="border-collapse:collapse;max-width:600px;width:100%;background:#fff;border-radius:14px;overflow:hidden;box-shadow:0 4px 24px rgba(16,40,80,0.10);">

        <!-- ── Header band with the title on top ── -->
        <tr>
          <td style="background:linear-gradient(135deg,#8b14d4,#4a0080);padding:30px 32px;text-align:center;">
            <div style="color:rgba(255,255,255,0.75);font-size:12px;letter-spacing:1px;text-transform:uppercase;margin-bottom:8px;">Quality Registrar Systems</div>
            <h1 style="color:#fff;font-size:23px;font-weight:700;margin:0;line-height:1.25;">
              Certification Report
            </h1>
            <div style="color:#fff;font-size:15px;margin-top:6px;font-weight:500;">${report.monthName} ${report.year}</div>
          </td>
        </tr>

        <!-- ── Summary line ── -->
        <tr>
          <td style="padding:28px 32px 6px;font-size:14px;line-height:1.7;color:#374151;">
            ${summary}
          </td>
        </tr>

        <!-- ── KPI cards ── -->
        <tr>
          <td style="padding:10px 26px 4px;">
            <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;"><tr>${cards}</tr></table>
          </td>
        </tr>

        <!-- ── Total strip ── -->
        <tr>
          <td style="padding:14px 32px 4px;">
            <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;background:#1a0440;border-radius:10px;">
              <tr>
                <td style="padding:14px 18px;color:#fff;font-size:14px;font-weight:600;">Total certificates due</td>
                <td style="padding:14px 18px;color:#fff;font-size:22px;font-weight:800;text-align:right;">${report.total}</td>
              </tr>
            </table>
          </td>
        </tr>

        <!-- ── Attachments note ── -->
        <tr>
          <td style="padding:18px 32px 4px;font-size:13px;color:#6b7280;line-height:1.6;">
            📎 The full breakdown is attached as <strong style="color:#1a0440;">Excel</strong> (one sheet per category) and <strong style="color:#1a0440;">PDF</strong>.
          </td>
        </tr>

        <!-- ── Footer ── -->
        <tr>
          <td style="background:#f8f5ff;padding:16px 32px;text-align:center;border-top:1px solid #ede8ff;">
            <p style="color:#9aa1ad;font-size:11px;margin:0;">© ${new Date().getFullYear()} Quality Registrar Systems · generated automatically</p>
          </td>
        </tr>
      </table>
    </div>`;
  }
}