import { NextResponse } from "next/server";
import { Resend } from "resend";
import { ZodError } from "zod";
import {
  type ContactFormResponse,
  contactFormSchema,
} from "@/data/contact-form";
import { opServer } from "@/lib/openpanel";

const RESEND_DOMAIN = process.env.RESEND_DOMAIN || "elevaseo.com";
const FROM_EMAIL = process.env.RESEND_FROM_EMAIL || `contact@${RESEND_DOMAIN}`;
const CC_EMAIL = process.env.RESEND_CC_EMAIL;
const WHITESPACE_REGEX = /\s+/;

function getResend(): Resend | null {
  const apiKey = process.env.RESEND_API_KEY;
  if (!apiKey) {
    return null;
  }
  return new Resend(apiKey);
}

/** Escape HTML special characters to prevent XSS in email templates */
function escapeHtml(str: string): string {
  return str
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
}

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const validatedData = contactFormSchema.parse(body);

    const { fullName, email, website, projectType, message } = validatedData;
    const firstName = fullName.trim().split(WHITESPACE_REGEX)[0] ?? fullName;

    const resend = getResend();

    // 1. Send contact notification email
    if (resend) {
      const { error } = await resend.emails.send({
        from: `ElevaSEO <${FROM_EMAIL}>`,
        to: FROM_EMAIL,
        ...(CC_EMAIL ? { cc: CC_EMAIL } : {}),
        replyTo: email,
        subject: `New contact message from ${escapeHtml(fullName)}`,
        html: buildNotificationHtml({
          fullName,
          email,
          website,
          projectType,
          message,
        }),
      });

      if (error) {
        console.error("Resend send error:", error);
        throw new Error(error.message);
      }

      // 2. Send confirmation email to user (non-blocking)
      resend.emails
        .send({
          from: `ElevaSEO <${FROM_EMAIL}>`,
          to: email,
          subject: "We received your message - ElevaSEO",
          html: buildConfirmationHtml(firstName),
        })
        .catch((err) => console.error("Confirmation email error:", err));
    } else {
      console.warn("RESEND_API_KEY not configured, skipping email");
    }

    // 3. Track contact form submission in OpenPanel
    opServer
      .track("contact_form_submitted", {
        projectType,
        website,
      })
      .catch((err) => console.error("OpenPanel tracking error:", err));

    const response: ContactFormResponse = {
      success: true,
      message:
        "Your message has been sent successfully! We will get back to you within 24 hours.",
      data: {
        emailId: `contact_${Date.now()}`,
        timestamp: new Date().toISOString(),
      },
    };

    return NextResponse.json(response, { status: 200 });
  } catch (error) {
    if (error instanceof ZodError) {
      const response: ContactFormResponse = {
        success: false,
        message: "Please correct the errors in the form.",
        error: "Validation failed",
      };
      return NextResponse.json(response, { status: 400 });
    }

    console.error("Contact form error:", error);
    const response: ContactFormResponse = {
      success: false,
      message: "A technical error occurred. Please try again.",
      error: "Internal server error",
    };
    return NextResponse.json(response, { status: 500 });
  }
}

// --- Email HTML builders ---

function buildNotificationHtml(data: {
  fullName: string;
  email: string;
  website: string;
  projectType: string;
  message?: string;
}): string {
  const name = escapeHtml(data.fullName);
  const email = escapeHtml(data.email);
  const website = escapeHtml(data.website);
  const projectType = escapeHtml(data.projectType);
  const messageHtml = data.message
    ? escapeHtml(data.message).replace(/\n/g, "<br>")
    : "<em>No message provided.</em>";

  return `
    <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
      <h2 style="color: #FD105E;">New Contact Message</h2>

      <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0;">
        <h3 style="margin-top: 0; color: #333;">Contact Information</h3>
        <p><strong>Name:</strong> ${name}</p>
        <p><strong>Email:</strong> <a href="mailto:${email}">${email}</a></p>
        <p><strong>Website:</strong> <a href="${website}" target="_blank">${website}</a></p>
        <p><strong>Project Type:</strong> ${projectType}</p>
      </div>

      <div style="background: #fff; padding: 20px; border-left: 4px solid #FD105E; margin: 20px 0;">
        <h3 style="margin-top: 0; color: #333;">Message</h3>
        <p style="line-height: 1.6; color: #555;">${messageHtml}</p>
      </div>

      <div style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee; color: #666; font-size: 12px;">
        <p>Sent from ElevaSEO contact form</p>
        <p>Date: ${new Date().toISOString()}</p>
      </div>
    </div>
  `;
}

function buildConfirmationHtml(firstName: string): string {
  const name = escapeHtml(firstName);

  return `
    <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
      <div style="background: linear-gradient(135deg, #000 0%, #1A2428 100%); padding: 40px 20px; text-align: center; border-radius: 8px 8px 0 0;">
        <h1 style="color: #FD105E; margin: 0; font-size: 28px;">ElevaSEO</h1>
        <p style="color: white; margin: 10px 0 0 0; font-size: 16px;">Performance Engineering for Growth Teams</p>
      </div>

      <div style="background: white; padding: 30px 20px; border-radius: 0 0 8px 8px;">
        <h2 style="color: #333; margin-top: 0;">Hello ${name},</h2>

        <p style="color: #555; line-height: 1.6;">
          We have received your message and thank you for reaching out. Our team is reviewing it carefully
          and will respond within <strong>24 hours</strong>.
        </p>

        <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0;">
          <h3 style="color: #FD105E; margin-top: 0;">Next Steps</h3>
          <ul style="color: #555; line-height: 1.6; margin: 0; padding-left: 20px;">
            <li>Analysis of your request by our team</li>
            <li>Preparation of a personalized proposal</li>
            <li>Contact to discuss your project</li>
          </ul>
        </div>

        <p style="color: #555; line-height: 1.6;">
          In the meantime, feel free to check out our
          <a href="https://www.elevaseo.com/services" style="color: #FD105E; text-decoration: none;">services</a>
          to discover our expertise.
        </p>

        <div style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee;">
          <p style="color: #666; margin: 0;">
            Best regards,<br>
            <strong style="color: #FD105E;">The ElevaSEO Team</strong>
          </p>
        </div>
      </div>

      <div style="text-align: center; margin-top: 20px; color: #666; font-size: 12px;">
        <p>&copy; ${new Date().getFullYear()} ElevaSEO</p>
      </div>
    </div>
  `;
}
