import { Request, Response, NextFunction } from 'express';
import * as emailTemplatesRepo from '../repositories/emailTemplates.repository';
import { buildMasterEmailHtml, replacePlaceholders } from '../utils/emailTemplateRenderer';
import { sendAndLogEmail } from '../services/notificationSender.service';
import { sendSuccess, sendError } from '../utils/apiResponse';

export const list = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const templates = await emailTemplatesRepo.findAll();
    return sendSuccess(res, 200, 'Modèles d\'e-mails récupérés avec succès', templates);
  } catch (error) {
    next(error);
  }
};

export const getOne = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const key = req.params.key as string;
    const template = await emailTemplatesRepo.findByKey(key);
    if (!template) {
      return sendError(res, 404, 'Modèle d\'e-mail introuvable');
    }
    return sendSuccess(res, 200, 'Modèle d\'e-mail récupéré', template);
  } catch (error) {
    next(error);
  }
};

export const update = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const key = req.params.key as string;
    const { name, subject, headline, body_content, action_button_text, action_button_url, footer_note, is_active } = req.body;

    const existing = await emailTemplatesRepo.findByKey(key);
    if (!existing) {
      return sendError(res, 404, 'Modèle d\'e-mail introuvable');
    }

    const updated = await emailTemplatesRepo.update(key, {
      name,
      subject,
      headline,
      body_content,
      action_button_text,
      action_button_url,
      footer_note,
      is_active,
    });

    return sendSuccess(res, 200, 'Modèle d\'e-mail mis à jour avec succès', updated);
  } catch (error) {
    next(error);
  }
};

export const preview = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const key = req.params.key as string;
    const { subject, headline, body_content, action_button_text, action_button_url, footer_note, sampleVariables } = req.body;

    const template = await emailTemplatesRepo.findByKey(key);
    if (!template && !body_content) {
      return sendError(res, 404, 'Modèle d\'e-mail introuvable');
    }

    const vars = sampleVariables || {
      prenom: 'Moussa',
      nom: 'Diop',
      email: 'moussa.diop@example.com',
      telephone: '+221 77 123 45 67',
      sujet: 'Demande d\'informations Appartement F4',
      montant: '15 000 000',
      projet: 'Résidence Union',
      lot: 'Apt B-204',
      echeance: 'Échéance N°2 - Gros Œuvre',
      datePaiement: '14 Octobre 2026',
      dateLimite: '25 Octobre 2026',
      modeReglement: 'Virement bancaire',
      reference: 'VIR-2026-9812',
      resteAPayer: '35 000 000',
      loginUrl: 'https://fbk.samafamille.com/login',
      portalUrl: 'https://fbk.samafamille.com/portal',
      motDePasse: 'TempPass2026!',
    };

    const finalSubject = replacePlaceholders(subject || template?.subject || '', vars);
    const finalHeadline = replacePlaceholders(headline ?? template?.headline ?? '', vars);
    const finalBody = replacePlaceholders(body_content || template?.body_content || '', vars);
    const finalBtnText = replacePlaceholders(action_button_text ?? template?.action_button_text ?? '', vars);
    const finalBtnUrl = replacePlaceholders(action_button_url ?? template?.action_button_url ?? '', vars);
    const finalFooter = replacePlaceholders(footer_note ?? template?.footer_note ?? '', vars);

    const html = buildMasterEmailHtml({
      headline: finalHeadline,
      bodyContent: finalBody,
      buttonText: finalBtnText || null,
      buttonUrl: finalBtnUrl || null,
      footerNote: finalFooter || null,
    });

    return sendSuccess(res, 200, 'Aperçu généré avec succès', {
      subject: finalSubject,
      html,
    });
  } catch (error) {
    next(error);
  }
};

export const sendTest = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const key = req.params.key as string;
    const { targetEmail } = req.body;

    const recipient = targetEmail?.trim() || req.user?.email || 'abdoilniang00@gmail.com';
    const template = await emailTemplatesRepo.findByKey(key);

    if (!template) {
      return sendError(res, 404, 'Modèle d\'e-mail introuvable');
    }

    const vars = {
      prenom: 'Testeur',
      nom: 'FBK Admin',
      email: recipient,
      telephone: '+221 76 605 18 18',
      sujet: 'Test de personnalisation du modèle',
      montant: '25 000 000',
      projet: 'Résidence Union',
      lot: 'Apt 102',
      echeance: 'Appel de fonds N°1',
      datePaiement: 'Aujourd\'hui',
      dateLimite: 'Dans 7 jours',
      loginUrl: 'https://fbk.samafamille.com/login',
      portalUrl: 'https://fbk.samafamille.com/portal',
      motDePasse: 'MotDePasseTest123',
    };

    const finalSubject = `[TEST] ${replacePlaceholders(template.subject, vars)}`;
    const finalHeadline = template.headline ? replacePlaceholders(template.headline, vars) : null;
    const finalBody = replacePlaceholders(template.body_content, vars);
    const finalBtnText = template.action_button_text ? replacePlaceholders(template.action_button_text, vars) : null;
    const finalBtnUrl = template.action_button_url ? replacePlaceholders(template.action_button_url, vars) : null;
    const finalFooter = template.footer_note ? replacePlaceholders(template.footer_note, vars) : null;

    const html = buildMasterEmailHtml({
      headline: finalHeadline,
      bodyContent: finalBody,
      buttonText: finalBtnText,
      buttonUrl: finalBtnUrl,
      footerNote: finalFooter,
    });

    const result = await sendAndLogEmail({
      to: recipient,
      recipientName: 'Administrateur Test',
      subject: finalSubject,
      html,
      emailType: `TEST_${key}`,
      metadata: {
        isTest: true,
        templateKey: key,
      },
    });

    return sendSuccess(res, 200, `E-mail de test envoyé à ${recipient}`, result);
  } catch (error: any) {
    return sendError(res, 500, error?.message || 'Erreur lors de l\'envoi du test');
  }
};
