import * as emailTemplatesRepo from '../repositories/emailTemplates.repository';

export interface RenderTemplateOptions {
  templateKey: string;
  variables: Record<string, string | number | undefined | null>;
  extraContentHtml?: string; // Blocs dynamiques complexes (ex: tableau des montants, identifiants temporaires)
}

export interface RenderedTemplateResult {
  subject: string;
  html: string;
  isCustom: boolean;
}

/**
 * Remplace tous les {{placeholder}} par leur valeur
 */
export const replacePlaceholders = (text: string, variables: Record<string, any>): string => {
  if (!text) return '';
  return text.replace(/\{\{\s*([a-zA-Z0-9_-]+)\s*\}\}/g, (_, key) => {
    const val = variables[key];
    return val !== undefined && val !== null ? String(val) : '';
  });
};

/**
 * Construit le gabarit HTML premium FBK Immo
 */
export const buildMasterEmailHtml = (params: {
  headline?: string | null;
  bodyContent: string;
  extraHtml?: string;
  buttonText?: string | null;
  buttonUrl?: string | null;
  footerNote?: string | null;
}): string => {
  const {
    headline = 'Excellence & Prestige Immobilier',
    bodyContent,
    extraHtml = '',
    buttonText,
    buttonUrl,
    footerNote,
  } = params;

  // Conversion des retours à la ligne en paragraphes propres
  const formattedBody = bodyContent
    .split(/\n\n+/)
    .map((paragraph) => `<p style="margin: 0 0 16px 0; font-size: 14px; line-height: 1.6; color: #334155;">${paragraph.replace(/\n/g, '<br />')}</p>`)
    .join('');

  return `
    <div style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; max-width: 620px; margin: 0 auto; background: #ffffff; border: 1px solid #e2e8f0; border-radius: 14px; overflow: hidden; box-shadow: 0 4px 14px rgba(0,0,0,0.06);">
      <!-- Header -->
      <div style="background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%); padding: 28px 24px; text-align: center; border-bottom: 3px solid #d97706;">
        <h1 style="color: #f59e0b; font-size: 23px; margin: 0; font-weight: 700; letter-spacing: 0.5px;">FBK Immo & Services</h1>
        ${headline ? `<p style="color: #cbd5e1; font-size: 13px; margin: 6px 0 0 0;">${headline}</p>` : ''}
      </div>

      <!-- Main Body -->
      <div style="padding: 28px 24px;">
        ${formattedBody}

        ${extraHtml ? `<div style="margin: 20px 0;">${extraHtml}</div>` : ''}

        ${
          buttonText && buttonUrl
            ? `
          <div style="text-align: center; margin: 28px 0;">
            <a href="${buttonUrl}" style="display: inline-block; background: #d97706; color: #ffffff; padding: 12px 28px; border-radius: 8px; font-weight: 600; font-size: 14px; text-decoration: none; box-shadow: 0 2px 6px rgba(217, 119, 6, 0.3);">
              ${buttonText}
            </a>
          </div>
        `
            : ''
        }

        ${
          footerNote
            ? `
          <div style="background: #f8fafc; border-left: 4px solid #d97706; padding: 14px 18px; border-radius: 6px; margin: 24px 0; font-size: 13px; color: #334155; line-height: 1.5;">
            ${footerNote}
          </div>
        `
            : ''
        }

        <p style="margin-top: 24px; margin-bottom: 0; font-size: 14px; color: #334155;">
          Bien cordialement,<br />
          <strong style="color: #0f172a;">L'équipe FBK Immo & Services</strong>
        </p>
      </div>

      <!-- Footer -->
      <div style="background: #f8fafc; padding: 18px; text-align: center; font-size: 12px; color: #94a3b8; border-top: 1px solid #e2e8f0; line-height: 1.5;">
        Ouakam Corniche L.91, Dakar, Sénégal • Tél : +221 76 605 18 18 • contact : abdoilniang00@gmail.com
      </div>
    </div>
  `;
};

/**
 * Récupère le modèle en base, applique les variables et génère l'email final
 */
export const renderEmailFromTemplate = async (
  options: RenderTemplateOptions
): Promise<RenderedTemplateResult | null> => {
  const { templateKey, variables, extraContentHtml } = options;

  try {
    const template = await emailTemplatesRepo.findByKey(templateKey);
    if (!template || !template.is_active) {
      return null;
    }

    const subject = replacePlaceholders(template.subject, variables);
    const headline = template.headline ? replacePlaceholders(template.headline, variables) : null;
    const bodyContent = replacePlaceholders(template.body_content, variables);
    const buttonText = template.action_button_text ? replacePlaceholders(template.action_button_text, variables) : null;
    const buttonUrl = template.action_button_url ? replacePlaceholders(template.action_button_url, variables) : null;
    const footerNote = template.footer_note ? replacePlaceholders(template.footer_note, variables) : null;

    const html = buildMasterEmailHtml({
      headline,
      bodyContent,
      extraHtml: extraContentHtml,
      buttonText,
      buttonUrl,
      footerNote,
    });

    return {
      subject,
      html,
      isCustom: true,
    };
  } catch (error) {
    console.warn(`Could not render template ${templateKey}, using fallback:`, error);
    return null;
  }
};
