import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import DOMPurify from "isomorphic-dompurify";
import validator from "validator";
import { logger } from "@/lib/logger";
import { getClientIp } from "@/lib/utils/ip-extraction";
import { v4 as uuidv4 } from "uuid";
import { createId } from "@paralleldrive/cuid2";
import { withSecureRoute } from "@/lib/api-security";
import { rateLimiters } from "@/lib/rate-limiter";
import * as LeadCRM from "@/lib/services/lead-crm.service";
import { sendEmail } from "@/lib/services/email";
import { prisma } from "@/lib/db";

// =============================================================================
// Validation
// =============================================================================

const roiReportSchema = z.object({
  // Lead info
  name: z.string().min(2).max(100),
  email: z.string().email(),
  phone: z.string().max(20).optional(),
  company: z.string().max(200).optional(),
  language: z.enum(["ar", "en"]).default("en"),
  recaptchaToken: z.string().optional(),
  // Calculator inputs
  calculator: z.object({
    industry: z.string(),
    country: z.string().length(2),
    countryName: z.string(),
    currency: z.string(),
    currencySymbol: z.string(),
    monthlyAppointments: z.number().min(1).max(10000),
    avgAppointmentValue: z.number().min(1),
    noShowRate: z.number().min(0).max(100),
    receptionistSalary: z.number().min(0),
    receptionistCount: z.number().min(0).max(10),
    // Computed results
    annualNoShowLoss: z.number(),
    receptionistCost: z.number(),
    mawidiAnnualCost: z.number(),
    recoveredRevenue: z.number(),
    netSavings: z.number(),
    roi: z.number(),
    paybackDays: z.number(),
  }),
});

// =============================================================================
// reCAPTCHA verification
// =============================================================================

async function verifyRecaptcha(
  token: string,
): Promise<{ success: boolean; score: number }> {
  const secretKey = process.env.RECAPTCHA_SECRET_KEY;
  const threshold = parseFloat(process.env.RECAPTCHA_SCORE_THRESHOLD || "0.5");

  if (process.env.NODE_ENV !== "production") {
    return { success: true, score: 1.0 };
  }

  if (!secretKey || !token) {
    return { success: false, score: 0 };
  }

  try {
    const response = await fetch(
      "https://www.google.com/recaptcha/api/siteverify",
      {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: `secret=${secretKey}&response=${token}`,
      },
    );
    const data = await response.json();
    return {
      success: data.success && data.score >= threshold,
      score: data.score || 0,
    };
  } catch {
    return { success: false, score: 0 };
  }
}

// =============================================================================
// HTML Report Generator
// =============================================================================

function generateReportHTML(data: {
  name: string;
  company: string;
  calculator: z.infer<typeof roiReportSchema>["calculator"];
  language: "ar" | "en";
}): string {
  const { name, company, calculator: c, language } = data;
  const isAr = language === "ar";
  const dir = isAr ? "rtl" : "ltr";
  const align = isAr ? "right" : "left";
  const fmt = (n: number) => n.toLocaleString(isAr ? "ar-SA" : "en-US");

  const recommendedPlan =
    c.monthlyAppointments > 500
      ? { nameEn: "Business", nameAr: "الأعمال", priceGBP: 249 }
      : c.monthlyAppointments > 200
        ? { nameEn: "Professional", nameAr: "المحترف", priceGBP: 209 }
        : { nameEn: "Starter", nameAr: "المبتدئ", priceGBP: 179 };

  return `<!DOCTYPE html>
<html dir="${dir}" lang="${language}">
<head>
  <meta charset="UTF-8">
  <style>
    body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; margin: 0; padding: 0; background: #f8fafc; color: #1e293b; direction: ${dir}; }
    .container { max-width: 680px; margin: 0 auto; background: white; }
    .header { background: linear-gradient(135deg, #059669, #10b981); padding: 40px 32px; text-align: center; }
    .header h1 { color: white; font-size: 28px; margin: 0 0 8px; }
    .header p { color: rgba(255,255,255,0.9); font-size: 16px; margin: 0; }
    .logo { font-size: 32px; font-weight: bold; color: white; margin-bottom: 16px; }
    .section { padding: 32px; }
    .section h2 { color: #059669; font-size: 22px; margin: 0 0 16px; border-bottom: 2px solid #d1fae5; padding-bottom: 8px; }
    .metric-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin: 24px 0; }
    .metric { background: #f0fdf4; border-radius: 12px; padding: 20px; text-align: center; }
    .metric .value { font-size: 28px; font-weight: bold; color: #059669; }
    .metric .label { font-size: 13px; color: #64748b; margin-top: 4px; }
    .metric.danger { background: #fef2f2; }
    .metric.danger .value { color: #dc2626; }
    table { width: 100%; border-collapse: collapse; margin: 16px 0; }
    th, td { padding: 12px 16px; text-align: ${align}; border-bottom: 1px solid #e2e8f0; }
    th { background: #f1f5f9; font-weight: 600; color: #475569; }
    .highlight { background: #f0fdf4; font-weight: 600; color: #059669; }
    .bar-chart { margin: 24px 0; }
    .bar { height: 32px; border-radius: 6px; margin: 8px 0; display: flex; align-items: center; padding: 0 12px; color: white; font-weight: 600; font-size: 14px; }
    .bar.current { background: #dc2626; }
    .bar.mawidi { background: #059669; }
    .cta { background: linear-gradient(135deg, #059669, #10b981); padding: 32px; text-align: center; border-radius: 12px; margin: 24px 0; }
    .cta h3 { color: white; font-size: 20px; margin: 0 0 8px; }
    .cta p { color: rgba(255,255,255,0.9); margin: 0 0 16px; }
    .cta a { display: inline-block; background: white; color: #059669; padding: 12px 32px; border-radius: 8px; text-decoration: none; font-weight: 700; }
    .footer { padding: 24px 32px; text-align: center; color: #94a3b8; font-size: 12px; border-top: 1px solid #e2e8f0; }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <div class="logo">Mawidi | ${isAr ? "موعدي" : "مَوعدي"}</div>
      <h1>${isAr ? "تقرير العائد على الاستثمار المخصص" : "Your Personalized ROI Report"}</h1>
      <p>${isAr ? `أُعدّ خصيصاً لـ ${company || name}` : `Prepared for ${company || name}`}</p>
    </div>

    <div class="section">
      <h2>${isAr ? "الوضع الحالي: ما تخسره الآن" : "Current Situation: What You're Losing"}</h2>
      <div class="metric-grid">
        <div class="metric danger">
          <div class="value">${c.currencySymbol} ${fmt(c.annualNoShowLoss)}</div>
          <div class="label">${isAr ? "خسائر عدم الحضور السنوية" : "Annual No-Show Losses"}</div>
        </div>
        <div class="metric danger">
          <div class="value">${c.currencySymbol} ${fmt(c.receptionistCost)}</div>
          <div class="label">${isAr ? "تكلفة الاستقبال السنوية" : "Annual Receptionist Cost"}</div>
        </div>
        <div class="metric danger">
          <div class="value">${c.noShowRate}%</div>
          <div class="label">${isAr ? "معدل عدم الحضور" : "No-Show Rate"}</div>
        </div>
        <div class="metric danger">
          <div class="value">${fmt(Math.round(c.monthlyAppointments * (c.noShowRate / 100)))}</div>
          <div class="label">${isAr ? "مواعيد مفقودة/شهر" : "Lost Appointments/Month"}</div>
        </div>
      </div>
    </div>

    <div class="section">
      <h2>${isAr ? "مع موعدي: ما ستوفره" : "With Mawidi: What You'll Save"}</h2>
      <div class="metric-grid">
        <div class="metric">
          <div class="value">${c.currencySymbol} ${fmt(Math.round(c.netSavings))}</div>
          <div class="label">${isAr ? "صافي التوفير في السنة الأولى" : "Net Savings in Year 1"}</div>
        </div>
        <div class="metric">
          <div class="value">${Math.round(c.roi)}%</div>
          <div class="label">${isAr ? "العائد على الاستثمار" : "Return on Investment"}</div>
        </div>
        <div class="metric">
          <div class="value">${c.paybackDays} ${isAr ? "يوم" : "days"}</div>
          <div class="label">${isAr ? "فترة الاسترداد" : "Payback Period"}</div>
        </div>
        <div class="metric">
          <div class="value">${c.currencySymbol} ${fmt(Math.round(c.recoveredRevenue))}</div>
          <div class="label">${isAr ? "الإيرادات المستردة" : "Recovered Revenue"}</div>
        </div>
      </div>
    </div>

    <div class="section">
      <h2>${isAr ? "تفاصيل التكلفة" : "Cost Breakdown"}</h2>
      <table>
        <tr><th>${isAr ? "البند" : "Item"}</th><th>${isAr ? "المبلغ السنوي" : "Annual Amount"}</th></tr>
        <tr><td>${isAr ? "خسائر عدم الحضور (الحالية)" : "No-Show Losses (Current)"}</td><td class="highlight" style="color:#dc2626">${c.currencySymbol} ${fmt(c.annualNoShowLoss)}</td></tr>
        <tr><td>${isAr ? "تكلفة الاستقبال" : "Receptionist Cost"}</td><td>${c.currencySymbol} ${fmt(c.receptionistCost)}</td></tr>
        <tr><td>${isAr ? "تكلفة موعدي السنوية" : "Mawidi Annual Cost"}</td><td>${c.currencySymbol} ${fmt(Math.round(c.mawidiAnnualCost))}</td></tr>
        <tr><td>${isAr ? "الإيرادات المستردة (تقليل 70%)" : "Recovered Revenue (70% reduction)"}</td><td class="highlight">${c.currencySymbol} ${fmt(Math.round(c.recoveredRevenue))}</td></tr>
        <tr style="background:#f0fdf4;font-weight:700"><td>${isAr ? "صافي التوفير" : "Net Savings"}</td><td style="color:#059669;font-size:18px">${c.currencySymbol} ${fmt(Math.round(c.netSavings))}</td></tr>
      </table>
    </div>

    <div class="section">
      <h2>${isAr ? "المقارنة البصرية" : "Visual Comparison"}</h2>
      <div class="bar-chart">
        <p style="margin:0 0 4px;font-size:13px;color:#64748b">${isAr ? "التكلفة الحالية (عدم الحضور + الاستقبال)" : "Current Cost (No-Shows + Receptionist)"}</p>
        <div class="bar current" style="width:100%">${c.currencySymbol} ${fmt(c.annualNoShowLoss + c.receptionistCost)}</div>
        <p style="margin:16px 0 4px;font-size:13px;color:#64748b">${isAr ? "مع موعدي" : "With Mawidi"}</p>
        <div class="bar mawidi" style="width:${Math.max(10, Math.round((c.mawidiAnnualCost / (c.annualNoShowLoss + c.receptionistCost)) * 100))}%">${c.currencySymbol} ${fmt(Math.round(c.mawidiAnnualCost))}</div>
      </div>
    </div>

    <div class="section">
      <h2>${isAr ? "كيف يعمل موعدي لعيادتك" : "How Mawidi Works for Your Clinic"}</h2>
      <table>
        <tr><td>1.</td><td>${isAr ? "المرضى يحجزون عبر واتساب 24/7 — لا حاجة لموظفة استقبال" : "Patients book via WhatsApp 24/7 — no receptionist needed"}</td></tr>
        <tr><td>2.</td><td>${isAr ? "تذكيرات آلية تقلل عدم الحضور بنسبة تصل إلى 70%" : "Automated reminders reduce no-shows by up to 70%"}</td></tr>
        <tr><td>3.</td><td>${isAr ? "تحصيل العربون عبر رابط دفع فوري يؤكد الالتزام" : "Deposit collection via instant payment link confirms commitment"}</td></tr>
        <tr><td>4.</td><td>${isAr ? "إعادة الجدولة الذكية تملأ الفراغات تلقائياً" : "Smart rescheduling fills gaps automatically"}</td></tr>
        <tr><td>5.</td><td>${isAr ? "لوحة تحكم CRM متكاملة لإدارة المرضى والتحليلات" : "Full CRM dashboard for patient management and analytics"}</td></tr>
      </table>
    </div>

    <div class="section">
      <h2>${isAr ? "الباقة الموصى بها" : "Recommended Plan"}</h2>
      <div style="background:#f0fdf4;border:2px solid #059669;border-radius:12px;padding:24px;text-align:center">
        <p style="font-size:24px;font-weight:700;color:#059669;margin:0">${isAr ? recommendedPlan.nameAr : recommendedPlan.nameEn}</p>
        <p style="font-size:18px;color:#475569;margin:8px 0">${isAr ? "ابتداءً من" : "Starting at"} &pound;${recommendedPlan.priceGBP}/${isAr ? "شهر" : "month"}</p>
        <p style="font-size:14px;color:#64748b;margin:0">${isAr ? "بناءً على حجم مواعيدك الشهرية" : `Based on your ${fmt(c.monthlyAppointments)} monthly appointments`}</p>
      </div>
    </div>

    <div class="section">
      <div class="cta">
        <h3>${isAr ? "جاهز لتوفير المال؟" : "Ready to Start Saving?"}</h3>
        <p>${isAr ? "ابدأ تجربتك المجانية لمدة 14 يوماً — بدون بطاقة ائتمان" : "Start your 14-day free trial — no credit card required"}</p>
        <a href="https://mawidi.com/en/signup?plan=tier2&source=roi-report">${isAr ? "ابدأ التجربة المجانية" : "Start Free Trial"}</a>
      </div>
    </div>

    <div class="footer">
      <p>Mawidi | AI-Powered Appointment Management</p>
      <p>${isAr ? "هذا التقرير أُنشئ تلقائياً بناءً على البيانات المدخلة. النتائج الفعلية قد تختلف." : "This report was auto-generated based on your inputs. Actual results may vary."}</p>
      <p>&copy; ${new Date().getFullYear()} Mawidi. All rights reserved.</p>
    </div>
  </div>
</body>
</html>`;
}

// =============================================================================
// API Handler
// =============================================================================

/**
 * POST /api/tools/roi-report
 * Generate and email a personalized ROI report
 */
export const POST = withSecureRoute(
  async (request: NextRequest) => {
    try {
      const body = await request.json();
      const ip = getClientIp(request);

      // Validate input
      const validation = roiReportSchema.safeParse(body);
      if (!validation.success) {
        return NextResponse.json(
          { error: "Invalid input", details: validation.error.errors },
          { status: 400 },
        );
      }

      const {
        name,
        email,
        phone,
        company,
        language,
        recaptchaToken,
        calculator,
      } = validation.data;

      // Verify reCAPTCHA
      if (recaptchaToken) {
        const result = await verifyRecaptcha(recaptchaToken);
        if (!result.success) {
          return NextResponse.json(
            { error: "Bot verification failed" },
            { status: 400 },
          );
        }
      }

      // Validate email
      if (!validator.isEmail(email)) {
        return NextResponse.json(
          { error: "Invalid email address" },
          { status: 400 },
        );
      }

      // Sanitize inputs
      const sanitizedName = DOMPurify.sanitize(name);
      const sanitizedEmail = validator.normalizeEmail(email) || email;
      const sanitizedCompany = company ? DOMPurify.sanitize(company) : "";
      const sanitizedPhone = phone ? DOMPurify.sanitize(phone) : "";

      // Generate the HTML report
      const reportHTML = generateReportHTML({
        name: sanitizedName,
        company: sanitizedCompany,
        calculator,
        language,
      });

      // Save lead to database
      const leadId = uuidv4();

      // Create CRM lead with high priority (fire-and-forget)
      LeadCRM.createLead("system", {
        name: sanitizedName,
        email: sanitizedEmail,
        phone: sanitizedPhone,
        company: sanitizedCompany,
        source: "roi_calculator",
        sourceChannel: "website",
      }).catch((err: Error) => {
        logger.error("Failed to create CRM lead from ROI report", {
          error: err.message,
        });
      });

      // Create staff alert
      await prisma.staff_alerts.create({
        data: {
          id: createId(),
          type: "NEW_CONTACT",
          title:
            language === "ar"
              ? "عميل محتمل جديد - حاسبة ROI"
              : "New ROI Calculator Lead",
          message: `${sanitizedName}${sanitizedCompany ? ` (${sanitizedCompany})` : ""} - ${calculator.industry} in ${calculator.countryName}. Potential savings: ${calculator.currency} ${Math.round(calculator.netSavings).toLocaleString()}/yr (${Math.round(calculator.roi)}% ROI)`,
          severity: "INFO",
          metadata: {
            leadId,
            email: sanitizedEmail,
            phone: sanitizedPhone,
            company: sanitizedCompany,
            calculator,
          },
        },
      });

      // Send the report via email
      const isAr = language === "ar";
      const emailSent = await sendEmail(sanitizedEmail, {
        subject: isAr
          ? `تقرير العائد على الاستثمار - ${sanitizedCompany || sanitizedName}`
          : `Your ROI Report - ${sanitizedCompany || sanitizedName} | Mawidi`,
        html: reportHTML,
        text: isAr
          ? `مرحباً ${sanitizedName}،\n\nشكراً لاستخدام حاسبة العائد على الاستثمار من موعدي.\n\nنتائجك:\n- خسائر عدم الحضور السنوية: ${calculator.currency} ${calculator.annualNoShowLoss.toLocaleString()}\n- صافي التوفير مع موعدي: ${calculator.currency} ${Math.round(calculator.netSavings).toLocaleString()}/سنة\n- العائد على الاستثمار: ${Math.round(calculator.roi)}%\n- فترة الاسترداد: ${calculator.paybackDays} يوم\n\nابدأ تجربتك المجانية: https://mawidi.com/ar/signup?plan=tier2\n\nفريق موعدي`
          : `Hi ${sanitizedName},\n\nThank you for using Mawidi's ROI Calculator.\n\nYour results:\n- Annual No-Show Losses: ${calculator.currency} ${calculator.annualNoShowLoss.toLocaleString()}\n- Net Savings with Mawidi: ${calculator.currency} ${Math.round(calculator.netSavings).toLocaleString()}/year\n- ROI: ${Math.round(calculator.roi)}%\n- Payback Period: ${calculator.paybackDays} days\n\nStart your free trial: https://mawidi.com/en/signup?plan=tier2\n\nThe Mawidi Team`,
      });

      if (!emailSent) {
        logger.warn("ROI report email may have failed to send", {
          email: sanitizedEmail,
        });
      }

      logger.info("ROI report generated and sent", {
        leadId,
        email: sanitizedEmail,
        industry: calculator.industry,
        country: calculator.country,
        roi: Math.round(calculator.roi),
        netSavings: Math.round(calculator.netSavings),
      });

      return NextResponse.json({
        success: true,
        message: isAr
          ? "تم إرسال التقرير إلى بريدك الإلكتروني"
          : "Report sent to your email",
        leadId,
      });
    } catch (error) {
      logger.error("ROI report generation error:", { error });
      return NextResponse.json(
        { error: "Failed to generate report" },
        { status: 500 },
      );
    }
  },
  { rateLimiter: rateLimiters.contact },
);

export const runtime = "nodejs";
export const dynamic = "force-dynamic";
