"use server";

import { Resend } from "resend";
import {
  simulateurLeadSchema,
  type SimulateurLeadState,
} from "@/lib/validations/simulateur";
import { opServer } from "@/lib/openpanel";
import { captureSubscriber } from "@/lib/listmonk";

// Initialisation lazy pour éviter les erreurs si la clé n'est pas définie
function getResendClient() {
  const apiKey = process.env.RESEND_API_KEY;
  if (!apiKey) {
    throw new Error("RESEND_API_KEY is not configured");
  }
  return new Resend(apiKey);
}

/**
 * Simulateur Lead Form Server Action
 *
 * Handles lead capture after simulation with:
 * - Zod validation
 * - Honeypot spam protection
 * - Double email sending (notification + confirmation)
 * - OpenPanel server-side tracking
 *
 * Environment variables required:
 * - RESEND_API_KEY: Resend API key
 * - CONTACT_EMAIL_FROM: Sender email (default: onboarding@resend.dev)
 * - CONTACT_EMAIL_TO: Recipient email for notifications
 */
export async function submitSimulateurLead(
  prevState: SimulateurLeadState,
  formData: FormData,
): Promise<SimulateurLeadState> {
  // ═══════════════════════════════════════════════════════════
  // 1. VALIDATION ZOD
  // ═══════════════════════════════════════════════════════════
  const rawData = {
    email: formData.get("email"),
    phone: formData.get("phone"),
    company: formData.get("company"),
    nafCode: formData.get("nafCode"),
    annualConsumptionMWh: formData.get("annualConsumptionMWh"),
    estimatedSavings: formData.get("estimatedSavings"),
    bestTierCode: formData.get("bestTierCode"),
    website: formData.get("website"), // Honeypot
  };

  const validatedFields = simulateurLeadSchema.safeParse(rawData);

  if (!validatedFields.success) {
    return {
      errors: validatedFields.error.flatten().fieldErrors,
      success: false,
      message: "Veuillez corriger les erreurs du formulaire",
    };
  }

  const {
    email,
    phone,
    company,
    nafCode,
    annualConsumptionMWh,
    estimatedSavings,
    bestTierCode,
  } = validatedFields.data;

  // ═══════════════════════════════════════════════════════════
  // 2. VERIFICATION HONEYPOT (anti-bot)
  // ═══════════════════════════════════════════════════════════
  if (validatedFields.data.website) {
    console.warn("[SECURITY] Honeypot triggered:", {
      email,
      timestamp: new Date().toISOString(),
    });
    // Retour succes factice pour ne pas alerter le bot
    return {
      success: true,
      message: "Rapport envoyé avec succès !",
    };
  }

  const savingsFormatted = new Intl.NumberFormat("fr-FR", {
    style: "currency",
    currency: "EUR",
    maximumFractionDigits: 0,
  }).format(estimatedSavings);

  // Inscription Listmonk — sans `await`, planifie via after().
  captureSubscriber({
    email,
    name: company,
    source: "simulateur",
    attribs: {
      company,
      phone,
      naf: nafCode,
      conso_mwh: annualConsumptionMWh,
      economies_max: estimatedSavings,
      palier: bestTierCode,
    },
  });

  try {
    // ═══════════════════════════════════════════════════════════
    // 3. ENVOI EMAIL AU SUPPORT (notification interne)
    // ═══════════════════════════════════════════════════════════
    const resend = getResendClient();

    const { error: notificationError } = await resend.emails.send({
      from: process.env.CONTACT_EMAIL_FROM || "onboarding@resend.dev",
      to: [process.env.CONTACT_EMAIL_TO || "contact@votre-domaine.fr"],
      replyTo: email,
      subject: `[Simulateur] ${company} — Économie estimée: ${savingsFormatted}`,
      html: `
        <div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; color: #333;">

          <!-- En-tête -->
          <div style="background: linear-gradient(135deg, #ea580c 0%, #f97316 100%); padding: 24px; border-radius: 12px 12px 0 0; text-align: center;">
            <h1 style="color: white; margin: 0; font-size: 20px; font-weight: 600;">
              Nouveau lead — Simulateur Accise
            </h1>
          </div>

          <!-- Contenu principal -->
          <div style="background: #ffffff; padding: 24px; border: 1px solid #e5e7eb; border-top: none; border-radius: 0 0 12px 12px;">

            <!-- Économie estimée -->
            <div style="background: #fff7ed; border: 2px solid #ea580c; border-radius: 8px; padding: 16px; text-align: center; margin-bottom: 20px;">
              <div style="font-size: 12px; color: #9a3412; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 4px;">Économie annuelle estimée</div>
              <div style="font-size: 28px; font-weight: 700; color: #ea580c;">${savingsFormatted}</div>
            </div>

            <!-- Infos contact -->
            <table style="width: 100%; border-collapse: collapse; margin-bottom: 20px;">
              <tr>
                <td style="padding: 12px 16px; background: #f8fafc; border-radius: 8px;">
                  <div style="font-size: 12px; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 4px;">Entreprise</div>
                  <div style="font-size: 16px; font-weight: 600; color: #1e293b;">${company}</div>
                </td>
              </tr>
            </table>

            <table style="width: 100%; border-collapse: collapse; margin-bottom: 20px;">
              <tr>
                <td style="width: 50%; padding: 12px 16px; background: #f8fafc; border-radius: 8px 0 0 8px;">
                  <div style="font-size: 12px; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 4px;">Email</div>
                  <a href="mailto:${email}" style="font-size: 14px; color: #ea580c; text-decoration: none; font-weight: 500;">${email}</a>
                </td>
                <td style="width: 50%; padding: 12px 16px; background: #f8fafc; border-radius: 0 8px 8px 0;">
                  <div style="font-size: 12px; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 4px;">Téléphone</div>
                  <div style="font-size: 14px; color: #1e293b; font-weight: 500;">${phone}</div>
                </td>
              </tr>
            </table>

            <!-- Données simulateur -->
            <table style="width: 100%; border-collapse: collapse; margin-bottom: 20px;">
              <tr>
                <td style="width: 50%; padding: 12px 16px; background: #f8fafc; border-radius: 8px 0 0 8px;">
                  <div style="font-size: 12px; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 4px;">Code NAF</div>
                  <div style="font-size: 14px; color: #1e293b; font-weight: 500;">${nafCode}</div>
                </td>
                <td style="width: 50%; padding: 12px 16px; background: #f8fafc; border-radius: 0 8px 8px 0;">
                  <div style="font-size: 12px; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 4px;">Consommation</div>
                  <div style="font-size: 14px; color: #1e293b; font-weight: 500;">${annualConsumptionMWh} MWh/an</div>
                </td>
              </tr>
            </table>

            ${
              bestTierCode
                ? `
            <table style="width: 100%; border-collapse: collapse; margin-bottom: 20px;">
              <tr>
                <td style="padding: 12px 16px; background: #f8fafc; border-radius: 8px;">
                  <div style="font-size: 12px; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 4px;">Meilleur tier identifié</div>
                  <div style="font-size: 14px; color: #1e293b; font-weight: 500;">${bestTierCode}</div>
                </td>
              </tr>
            </table>
            `
                : ""
            }

            <!-- Actions -->
            <div style="text-align: center; padding-top: 16px; border-top: 1px solid #e5e7eb;">
              <a href="mailto:${email}" style="display: inline-block; background: #ea580c; color: white; padding: 12px 24px; border-radius: 8px; text-decoration: none; font-weight: 600; font-size: 14px;">
                Contacter ${company}
              </a>
            </div>
          </div>

          <!-- Footer -->
          <div style="text-align: center; padding: 16px; color: #94a3b8; font-size: 12px;">
            Reçu le ${new Date().toLocaleDateString("fr-FR", { day: "numeric", month: "long", year: "numeric" })} à ${new Date().toLocaleTimeString("fr-FR", { hour: "2-digit", minute: "2-digit", timeZone: "Europe/Paris" })}
          </div>
        </div>
      `,
    });

    if (notificationError) {
      console.error("[RESEND] Notification error:", notificationError);
      throw new Error("Email notification failed");
    }

    // ═══════════════════════════════════════════════════════════
    // 4. ENVOI EMAIL DE CONFIRMATION A L'UTILISATEUR
    // ═══════════════════════════════════════════════════════════
    const { error: confirmationError } = await resend.emails.send({
      from: process.env.CONTACT_EMAIL_FROM || "onboarding@resend.dev",
      to: [email],
      subject:
        "Votre rapport d'exonération d'accise — Acieb Énergie",
      html: `
        <div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; color: #333;">

          <!-- En-tête -->
          <div style="background: linear-gradient(135deg, #ea580c 0%, #f97316 100%); padding: 24px; border-radius: 12px 12px 0 0; text-align: center;">
            <h1 style="color: white; margin: 0; font-size: 20px; font-weight: 600;">
              Votre rapport d'exonération d'accise
            </h1>
            <p style="color: rgba(255,255,255,0.9); margin: 8px 0 0; font-size: 14px;">
              Acieb Énergie — Courtier en énergie B2B
            </p>
          </div>

          <!-- Contenu principal -->
          <div style="background: #ffffff; padding: 24px; border: 1px solid #e5e7eb; border-top: none; border-radius: 0 0 12px 12px;">

            <p style="color: #374151; line-height: 1.6; margin-bottom: 16px;">
              Bonjour,
            </p>

            <p style="color: #374151; line-height: 1.6; margin-bottom: 16px;">
              Merci d'avoir utilisé notre simulateur d'exonération d'accise sur l'électricité.
              Voici le résumé de votre simulation :
            </p>

            <!-- Résumé -->
            <div style="background: #fff7ed; border: 2px solid #ea580c; border-radius: 8px; padding: 20px; text-align: center; margin-bottom: 24px;">
              <div style="font-size: 12px; color: #9a3412; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 8px;">Économie annuelle estimée</div>
              <div style="font-size: 32px; font-weight: 700; color: #ea580c; margin-bottom: 4px;">${savingsFormatted}</div>
              <div style="font-size: 13px; color: #78716c;">Consommation : ${annualConsumptionMWh} MWh/an — Code NAF : ${nafCode}</div>
            </div>

            <!-- Prochaines étapes -->
            <h2 style="font-size: 16px; color: #1e293b; margin-bottom: 16px;">Prochaines étapes</h2>

            <div style="margin-bottom: 12px; padding: 12px 16px; background: #f8fafc; border-radius: 8px; border-left: 3px solid #ea580c;">
              <strong style="color: #1e293b;">1.</strong> <span style="color: #374151;">Rassemblez vos pièces justificatives (CERFA 16196*03)</span>
            </div>

            <div style="margin-bottom: 12px; padding: 12px 16px; background: #f8fafc; border-radius: 8px; border-left: 3px solid #ea580c;">
              <strong style="color: #1e293b;">2.</strong> <span style="color: #374151;">Un expert Acieb analysera votre dossier en détail</span>
            </div>

            <div style="margin-bottom: 24px; padding: 12px 16px; background: #f8fafc; border-radius: 8px; border-left: 3px solid #ea580c;">
              <strong style="color: #1e293b;">3.</strong> <span style="color: #374151;">Nous vous accompagnons dans vos démarches de remboursement</span>
            </div>

            <!-- CTA -->
            <div style="text-align: center; margin-bottom: 24px;">
              <a href="https://aciebenergie.fr/contact" style="display: inline-block; background: linear-gradient(135deg, #ea580c 0%, #f97316 100%); color: white; padding: 14px 32px; border-radius: 8px; text-decoration: none; font-weight: 600; font-size: 15px;">
                Planifier un rendez-vous gratuit
              </a>
            </div>

            <div style="margin: 24px 0; padding: 16px; background-color: #fef3c7; border-left: 4px solid #ea580c; border-radius: 0 8px 8px 0;">
              <p style="margin: 0; color: #92400e; font-size: 14px;">
                <strong>Le saviez-vous ?</strong> Vous pouvez demander un remboursement rétroactif sur les 2 dernières années.
                Contactez-nous pour maximiser vos économies.
              </p>
            </div>
          </div>

          <!-- Footer -->
          <div style="text-align: center; padding: 16px; color: #94a3b8; font-size: 12px;">
            <p style="margin: 0 0 8px;">Acieb Énergie — Courtier en énergie B2B</p>
            <p style="margin: 0;">Cet email est automatique. Pour toute question, contactez-nous sur
              <a href="https://aciebenergie.fr/contact" style="color: #ea580c; text-decoration: none;">aciebenergie.fr</a>
            </p>
          </div>
        </div>
      `,
    });

    if (confirmationError) {
      console.error("[RESEND] Confirmation error:", confirmationError);
      // Ne pas bloquer si seule la confirmation échoue
    }

    // ═══════════════════════════════════════════════════════════
    // 5. RETOUR SUCCES
    // ═══════════════════════════════════════════════════════════
    opServer.track("simulateur_lead_submitted", {
      company,
      nafCode,
      consumptionMWh: String(annualConsumptionMWh),
      estimatedSavings: String(estimatedSavings),
      bestTierCode: bestTierCode || "none",
    });

    console.log("[SIMULATEUR] Lead submitted successfully:", {
      email,
      company,
      nafCode,
      estimatedSavings,
      timestamp: new Date().toISOString(),
    });

    return {
      success: true,
      message:
        "Rapport envoyé avec succès ! Vérifiez votre boîte email.",
    };
  } catch (error) {
    console.error("[SIMULATEUR] Submission error:", error);

    return {
      success: false,
      message: "Une erreur est survenue. Veuillez réessayer plus tard.",
      errors: {
        _form: ["Erreur serveur temporaire"],
      },
    };
  }
}
