import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { resend } from "@/lib/resend";

const contactSchema = z.object({
  name: z
    .string()
    .min(2, "Le nom doit contenir au moins 2 caractères")
    .max(100, "Le nom est trop long"),
  email: z.string().email("Adresse email invalide"),
  subject: z.enum(["support", "commercial", "partenariat", "autre"], {
    errorMap: () => ({ message: "Sujet invalide" }),
  }),
  message: z
    .string()
    .min(10, "Le message doit contenir au moins 10 caractères")
    .max(2000, "Le message est trop long (max. 2000 caractères)"),
});

const SUBJECT_LABELS: Record<string, string> = {
  support: "Support technique",
  commercial: "Commercial",
  partenariat: "Partenariat",
  autre: "Autre",
};

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const parsed = contactSchema.safeParse(body);

    if (!parsed.success) {
      const firstError = parsed.error.errors[0]?.message ?? "Données invalides";
      return NextResponse.json({ error: firstError }, { status: 400 });
    }

    const { name, email, subject, message } = parsed.data;
    const adminEmail = process.env.ADMIN_EMAIL ?? "admin@nextcrm.fr";
    const subjectLabel = SUBJECT_LABELS[subject] ?? subject;

    // Email to admin
    await resend.emails.send({
      from: `NextCRM Contact <${process.env.RESEND_FROM_EMAIL ?? "noreply@nextcrm.fr"}>`,
      to: adminEmail,
      subject: `[Contact] ${subjectLabel} — ${name}`,
      html: `
        <!DOCTYPE html>
        <html lang="fr">
        <head><meta charset="UTF-8" /></head>
        <body style="font-family: system-ui, sans-serif; color: #1e293b; background: #f8fafc; padding: 32px;">
          <div style="max-width: 560px; margin: 0 auto; background: white; border-radius: 12px; padding: 32px; border: 1px solid #e2e8f0;">
            <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 24px;">
              <div style="background: #4f46e5; color: white; padding: 6px; border-radius: 8px; font-size: 14px; font-weight: bold;">N</div>
              <span style="font-weight: 700; font-size: 18px;">NextCRM</span>
              <span style="color: #94a3b8;">— Nouveau message de contact</span>
            </div>

            <table style="width: 100%; border-collapse: collapse; margin-bottom: 24px;">
              <tr>
                <td style="padding: 8px 0; color: #64748b; font-size: 13px; width: 110px;">Nom</td>
                <td style="padding: 8px 0; font-weight: 600;">${name}</td>
              </tr>
              <tr>
                <td style="padding: 8px 0; color: #64748b; font-size: 13px;">Email</td>
                <td style="padding: 8px 0;"><a href="mailto:${email}" style="color: #4f46e5;">${email}</a></td>
              </tr>
              <tr>
                <td style="padding: 8px 0; color: #64748b; font-size: 13px;">Sujet</td>
                <td style="padding: 8px 0;">
                  <span style="background: #eef2ff; color: #4338ca; padding: 2px 10px; border-radius: 999px; font-size: 12px; font-weight: 600;">
                    ${subjectLabel}
                  </span>
                </td>
              </tr>
            </table>

            <div style="background: #f8fafc; border-radius: 8px; padding: 16px; border-left: 3px solid #4f46e5;">
              <p style="margin: 0; font-size: 14px; line-height: 1.6; white-space: pre-wrap;">${message}</p>
            </div>

            <p style="margin-top: 24px; font-size: 12px; color: #94a3b8; border-top: 1px solid #f1f5f9; padding-top: 16px;">
              Message reçu le ${new Date().toLocaleDateString("fr-FR", {
                day: "numeric",
                month: "long",
                year: "numeric",
                hour: "2-digit",
                minute: "2-digit",
              })}
            </p>
          </div>
        </body>
        </html>
      `,
    });

    // Confirmation email to sender
    await resend.emails.send({
      from: `NextCRM <${process.env.RESEND_FROM_EMAIL ?? "noreply@nextcrm.fr"}>`,
      to: email,
      subject: "Nous avons bien reçu votre message — NextCRM",
      html: `
        <!DOCTYPE html>
        <html lang="fr">
        <head><meta charset="UTF-8" /></head>
        <body style="font-family: system-ui, sans-serif; color: #1e293b; background: #f8fafc; padding: 32px;">
          <div style="max-width: 560px; margin: 0 auto; background: white; border-radius: 12px; padding: 32px; border: 1px solid #e2e8f0;">
            <div style="text-align: center; margin-bottom: 24px;">
              <div style="display: inline-flex; align-items: center; justify-content: center; background: #4f46e5; width: 48px; height: 48px; border-radius: 12px; margin-bottom: 12px;">
                <span style="color: white; font-size: 20px; font-weight: bold;">N</span>
              </div>
              <h1 style="font-size: 20px; font-weight: 700; margin: 0;">Merci, ${name} !</h1>
            </div>

            <p style="color: #475569; line-height: 1.6;">
              Nous avons bien reçu votre message concernant <strong>${subjectLabel}</strong>.
              Notre équipe vous répondra dans les plus brefs délais, généralement sous 24 h ouvrées.
            </p>

            <div style="background: #f8fafc; border-radius: 8px; padding: 16px; margin: 20px 0; border: 1px solid #e2e8f0;">
              <p style="margin: 0; font-size: 13px; color: #64748b; font-style: italic; white-space: pre-wrap;">${message.substring(0, 200)}${message.length > 200 ? "…" : ""}</p>
            </div>

            <p style="color: #475569; font-size: 14px; line-height: 1.6;">
              En attendant, n'hésitez pas à consulter notre{" "}
              <a href="${process.env.NEXT_PUBLIC_APP_URL ?? "https://nextcrm.fr"}/tarifs" style="color: #4f46e5;">page tarifs</a>
              ou à <a href="${process.env.NEXT_PUBLIC_APP_URL ?? "https://nextcrm.fr"}/inscription" style="color: #4f46e5;">créer un compte gratuit</a>.
            </p>

            <p style="margin-top: 24px; font-size: 12px; color: #94a3b8; border-top: 1px solid #f1f5f9; padding-top: 16px; text-align: center;">
              © 2025 NextCRM — Comptabilité pour PME et indépendants
            </p>
          </div>
        </body>
        </html>
      `,
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("[API /contact]", error);
    return NextResponse.json(
      { error: "Erreur serveur. Veuillez réessayer dans quelques instants." },
      { status: 500 }
    );
  }
}
