import { Injectable, Logger } from '@nestjs/common';
import { Resend } from 'resend';

type SendRgcDecisionSubmittedToCdcParams = {
  to: string[];
  plenaryId: number;
  rgcDecisionId: number;
  plenaryName: string;
  ministryName: string;
  categoryName?: string | null;
  status?: string | null;
  decision?: string | null;
  submittedBy?: string | null;
};

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

  async sendRgcDecisionSubmittedToCdc(
    params: SendRgcDecisionSubmittedToCdcParams,
  ): Promise<string | null> {
    const apiKey = process.env.RESEND_API_KEY;
    const fromEmail = process.env.RESEND_FROM_EMAIL;

    if (!apiKey || !fromEmail) {
      this.logger.warn(
        'RESEND_API_KEY or RESEND_FROM_EMAIL is missing. Skip plenary email notification.',
      );

      return null;
    }

    const recipients = Array.from(
      new Set(
        params.to
          .map((email) => email.trim())
          .filter((email) => this.isValidEmail(email)),
      ),
    );

    if (recipients.length === 0) {
      this.logger.warn('Email recipients are empty. Skip plenary email.');

      return null;
    }

    const frontendUrl = (process.env.FRONTEND_URL || 'http://localhost:3000')
      .trim()
      .replace(/\/+$/, '');

    const detailUrl = `${frontendUrl}/cdc-gpsf/plenary/plenaries/${params.plenaryId}`;
    const subject = `RGC Decision Submitted to CDC G-PSF - ${params.plenaryName}`;

    try {
      const resend = new Resend(apiKey);

      const { data, error } = await resend.emails.send({
        from: fromEmail,
        to: recipients,
        subject,
        html: this.buildHtml({
          ...params,
          detailUrl,
        }),
        text: this.buildText({
          ...params,
          detailUrl,
        }),
      });

      if (error) {
        this.logger.error(
          `Failed to send RGC Decision submitted email: ${error.message}`,
        );

        return null;
      }

      this.logger.log(
        `RGC Decision submitted email sent. id=${data?.id || '-'}`,
      );

      return data?.id ? String(data.id) : null;
    } catch (error) {
      this.logger.error(
        'Unexpected error while sending RGC Decision submitted email.',
        error,
      );

      return null;
    }
  }

  private buildHtml(
    params: SendRgcDecisionSubmittedToCdcParams & {
      detailUrl: string;
    },
  ): string {
    return `
      <div style="font-family: Arial, sans-serif; line-height: 1.6; color: #111827;">
        <h2 style="margin: 0 0 14px; color: #1F6DB2;">
          RGC Decision Submitted to CDC G-PSF
        </h2>

        <p>
          <strong>${this.escapeHtml(params.ministryName)}</strong>
          submitted an RGC Decision to CDC G-PSF.
        </p>

        <table style="border-collapse: collapse; width: 100%; margin-top: 14px;">
          <tbody>
            <tr>
              <td style="padding: 8px; border: 1px solid #E5E7EB; width: 180px;">
                <strong>Plenary</strong>
              </td>
              <td style="padding: 8px; border: 1px solid #E5E7EB;">
                ${this.escapeHtml(params.plenaryName)}
              </td>
            </tr>

            <tr>
              <td style="padding: 8px; border: 1px solid #E5E7EB;">
                <strong>Ministry</strong>
              </td>
              <td style="padding: 8px; border: 1px solid #E5E7EB;">
                ${this.escapeHtml(params.ministryName)}
              </td>
            </tr>

            <tr>
              <td style="padding: 8px; border: 1px solid #E5E7EB;">
                <strong>Category</strong>
              </td>
              <td style="padding: 8px; border: 1px solid #E5E7EB;">
                ${this.escapeHtml(params.categoryName || '-')}
              </td>
            </tr>

            <tr>
              <td style="padding: 8px; border: 1px solid #E5E7EB;">
                <strong>Status</strong>
              </td>
              <td style="padding: 8px; border: 1px solid #E5E7EB;">
                ${this.escapeHtml(params.status || '-')}
              </td>
            </tr>

            <tr>
              <td style="padding: 8px; border: 1px solid #E5E7EB;">
                <strong>Submitted By</strong>
              </td>
              <td style="padding: 8px; border: 1px solid #E5E7EB;">
                ${this.escapeHtml(params.submittedBy || '-')}
              </td>
            </tr>
          </tbody>
        </table>

        <div style="margin-top: 18px;">
          <strong>RGC Decision:</strong>
          <div style="margin-top: 8px; padding: 12px; background: #F9FAFB; border: 1px solid #E5E7EB; border-radius: 8px;">
            ${this.renderEditorHtml(params.decision)}
          </div>
        </div>

        <p style="margin-top: 22px;">
          <a
            href="${this.escapeHtml(params.detailUrl)}"
            style="display: inline-block; padding: 10px 16px; background: #1F6DB2; color: #FFFFFF; text-decoration: none; border-radius: 6px; font-weight: 600;"
          >
            View Plenary Detail
          </a>
        </p>

        <p style="margin-top: 20px; color: #6B7280; font-size: 12px;">
          This is an automatic notification from G-PSF MIS.
        </p>
      </div>
    `;
  }

  private buildText(
    params: SendRgcDecisionSubmittedToCdcParams & {
      detailUrl: string;
    },
  ): string {
    return [
      'RGC Decision Submitted to CDC G-PSF',
      '',
      `Plenary: ${params.plenaryName}`,
      `Ministry: ${params.ministryName}`,
      `Category: ${params.categoryName || '-'}`,
      `Status: ${params.status || '-'}`,
      `Submitted By: ${params.submittedBy || '-'}`,
      '',
      `Decision: ${this.stripHtml(params.decision || '-')}`,
      '',
      `View Detail: ${params.detailUrl}`,
    ].join('\n');
  }

  private renderEditorHtml(value?: string | null): string {
    if (!value?.trim()) {
      return '-';
    }

    return value
      .replace(/<script[\s\S]*?>[\s\S]*?<\/script>/gi, '')
      .replace(/on\w+="[^"]*"/gi, '')
      .replace(/on\w+='[^']*'/gi, '')
      .replace(/javascript:/gi, '');
  }

  private stripHtml(value: string): string {
    return value
      .replace(/<br\s*\/?>/gi, '\n')
      .replace(/<\/p>/gi, '\n')
      .replace(/<\/div>/gi, '\n')
      .replace(/<[^>]*>/g, ' ')
      .replace(/&nbsp;/gi, ' ')
      .replace(/&amp;/gi, '&')
      .replace(/&lt;/gi, '<')
      .replace(/&gt;/gi, '>')
      .replace(/\s+/g, ' ')
      .trim();
  }

  private escapeHtml(value: string): string {
    return value
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#039;');
  }

  private isValidEmail(value?: string | null): value is string {
    if (!value) {
      return false;
    }

    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim());
  }
}
