import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class EmailService {
  private readonly logger = new Logger(EmailService.name);
  private transporter: any = null;

  constructor(private config: ConfigService) {}

  private async getTransporter() {
    if (this.transporter) return this.transporter;
    const nodemailer = await import('nodemailer');
    this.transporter = nodemailer.createTransport({
      host:   this.config.get('SMTP_HOST'),
      port:   parseInt(this.config.get('SMTP_PORT') ?? '465'),
      secure: this.config.get('SMTP_SECURE') !== 'false',
      auth: {
        user: this.config.get('SMTP_USER'),
        pass: this.config.get('SMTP_PASS'),
      },
    });
    return this.transporter;
  }

  async send(to: string, subject: string, html: string) {
    const smtpHost = this.config.get('SMTP_HOST');
    if (!smtpHost) {
      this.logger.warn('SMTP not configured — email not sent');
      return;
    }
    try {
      const transport = await this.getTransporter();
      await transport.sendMail({
        from: this.config.get('SMTP_FROM') ?? `"Have Your Say" <noreply@haveyoursay.app>`,
        to,
        subject,
        html,
      });
      this.logger.log(`Email sent to ${to}: ${subject}`);
    } catch (err: any) {
      this.logger.error(`Email failed to ${to}: ${err.message}`);
    }
  }

  // ── Templates ─────────────────────────────────────────────────────────────────

  async sendWelcome(to: string, name: string) {
    const html = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Welcome to Have Your Say</title>
</head>
<body style="margin:0;padding:0;background:#f1f5f9;font-family:'Segoe UI',Arial,sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" style="background:#f1f5f9;padding:40px 16px;">
  <tr><td align="center">
    <table width="560" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:20px;overflow:hidden;box-shadow:0 4px 24px rgba(0,0,0,0.08);">

      <!-- Header -->
      <tr><td style="background:linear-gradient(135deg,#065f46 0%,#059669 100%);padding:40px 40px 32px;text-align:center;">
        <div style="width:72px;height:72px;background:rgba(255,255,255,0.15);border-radius:18px;margin:0 auto 20px;display:inline-flex;align-items:center;justify-content:center;border:2px solid rgba(110,231,183,0.4);">
          <span style="color:#ffffff;font-size:28px;font-weight:900;line-height:72px;display:block;">hys</span>
        </div>
        <h1 style="color:#ffffff;margin:0;font-size:26px;font-weight:800;letter-spacing:-0.5px;">Have Your Say</h1>
        <p style="color:rgba(110,231,183,0.9);margin:8px 0 0;font-size:14px;font-weight:500;">Your community, your voice</p>
      </td></tr>

      <!-- Body -->
      <tr><td style="padding:40px;">
        <h2 style="color:#0f172a;font-size:22px;font-weight:800;margin:0 0 12px;">Welcome aboard, ${name}! 🎉</h2>
        <p style="color:#475569;font-size:15px;line-height:1.7;margin:0 0 24px;">
          Thank you for joining <strong>Have Your Say</strong>. We're thrilled to have you as part of our community — a place where every voice matters and every opinion counts.
        </p>

        <!-- Info box -->
        <div style="background:#f0fdf4;border-radius:14px;padding:20px 24px;border-left:4px solid #059669;margin-bottom:28px;">
          <p style="color:#065f46;font-weight:700;font-size:14px;margin:0 0 6px;">⏳ Account under review</p>
          <p style="color:#475569;font-size:13px;line-height:1.6;margin:0;">
            Your account is currently being reviewed by our admin team. You'll receive another email once you're approved — usually within <strong>24–48 hours</strong>.
          </p>
        </div>

        <!-- What to expect -->
        <p style="color:#0f172a;font-weight:700;font-size:15px;margin:0 0 14px;">What you can look forward to:</p>
        <table cellpadding="0" cellspacing="0" width="100%">
          ${[
            ['📝', 'Post updates, start debates and share your ideas'],
            ['📊', 'Vote on polls and help shape community decisions'],
            ['💬', 'Chat privately in groups with fellow members'],
            ['🔔', 'Get instant push notifications for what matters'],
          ].map(([icon, text]) => `
          <tr><td style="padding:8px 0;">
            <table cellpadding="0" cellspacing="0"><tr>
              <td style="width:36px;height:36px;background:#f0fdf4;border-radius:10px;text-align:center;vertical-align:middle;font-size:18px;">${icon}</td>
              <td style="padding-left:12px;color:#475569;font-size:14px;line-height:1.5;">${text}</td>
            </tr></table>
          </td></tr>`).join('')}
        </table>
      </td></tr>

      <!-- Footer -->
      <tr><td style="background:#f8fafc;padding:24px 40px;text-align:center;border-top:1px solid #e2e8f0;">
        <p style="color:#94a3b8;font-size:12px;margin:0 0 4px;">where voices find their home</p>
        <p style="color:#cbd5e1;font-size:11px;margin:0;">crafted with <span style="color:#ef4444;">♥</span> by Multiprong Technologies</p>
      </td></tr>

    </table>
  </td></tr>
</table>
</body>
</html>`;
    await this.send(to, `Welcome to Have Your Say, ${name}!`, html);
  }

  async sendPasswordReset(to: string, name: string, resetLink: string) {
    const html = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Reset Your Password</title>
</head>
<body style="margin:0;padding:0;background:#f1f5f9;font-family:'Segoe UI',Arial,sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" style="background:#f1f5f9;padding:40px 16px;">
  <tr><td align="center">
    <table width="560" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:20px;overflow:hidden;box-shadow:0 4px 24px rgba(0,0,0,0.08);">

      <!-- Header -->
      <tr><td style="background:linear-gradient(135deg,#065f46 0%,#059669 100%);padding:36px 40px;text-align:center;">
        <h1 style="color:#ffffff;margin:0;font-size:24px;font-weight:800;">🔐 Password Reset</h1>
        <p style="color:rgba(110,231,183,0.9);margin:8px 0 0;font-size:14px;">Have Your Say</p>
      </td></tr>

      <!-- Body -->
      <tr><td style="padding:40px;">
        <p style="color:#0f172a;font-size:16px;font-weight:700;margin:0 0 8px;">Hi ${name},</p>
        <p style="color:#475569;font-size:15px;line-height:1.7;margin:0 0 28px;">
          We received a request to reset your password. Tap the button below to set a new one. This link expires in <strong>30 minutes</strong>.
        </p>

        <!-- CTA Button -->
        <table cellpadding="0" cellspacing="0" width="100%" style="margin-bottom:28px;">
          <tr><td align="center">
            <a href="${resetLink}" style="display:inline-block;background:linear-gradient(135deg,#065f46,#059669);color:#ffffff;text-decoration:none;font-weight:800;font-size:15px;padding:15px 40px;border-radius:14px;letter-spacing:0.3px;">
              Reset My Password →
            </a>
          </td></tr>
        </table>

        <!-- Warning box -->
        <div style="background:#fefce8;border-radius:14px;padding:16px 20px;border-left:4px solid #f59e0b;margin-bottom:20px;">
          <p style="color:#92400e;font-weight:700;font-size:13px;margin:0 0 4px;">🔒 Security notice</p>
          <p style="color:#78350f;font-size:12px;line-height:1.6;margin:0;">If you didn't request this, you can safely ignore this email. Your password will not change.</p>
        </div>

        <p style="color:#94a3b8;font-size:12px;line-height:1.6;margin:0;">
          Button not working? Copy and paste this link:<br/>
          <span style="color:#059669;word-break:break-all;">${resetLink}</span>
        </p>
      </td></tr>

      <!-- Footer -->
      <tr><td style="background:#f8fafc;padding:24px 40px;text-align:center;border-top:1px solid #e2e8f0;">
        <p style="color:#94a3b8;font-size:12px;margin:0 0 4px;">where voices find their home</p>
        <p style="color:#cbd5e1;font-size:11px;margin:0;">crafted with <span style="color:#ef4444;">♥</span> by Multiprong Technologies</p>
      </td></tr>

    </table>
  </td></tr>
</table>
</body>
</html>`;
    await this.send(to, 'Reset your Have Your Say password', html);
  }
}
