"use client";

import React, { useState } from "react";
import { X, Download, CheckCircle, TrendingUp, Gift } from "lucide-react";
import { useExitIntent } from "@/hooks/useExitIntent";

export type PopupVariant = "guide" | "discount" | "newsletter" | "demo";

interface ExitIntentPopupProps {
  variant?: PopupVariant;
  language?: "ar" | "en";
  onSubmit?: (data: LeadData) => Promise<void>;
  onClose?: () => void;
  enabled?: boolean;
  cookieDays?: number;
}

export interface LeadData {
  name: string;
  email: string;
  company?: string;
  variant: PopupVariant;
  language: "ar" | "en";
}

const VARIANT_CONFIG = {
  guide: {
    icon: Download,
    titleEn: "Wait! Get Our Free WhatsApp Automation Guide",
    titleAr: "انتظر! احصل على دليلنا المجاني لأتمتة الواتساب",
    subtitleEn: "Learn how to automate 80% of your customer conversations",
    subtitleAr: "تعلم كيف تقوم بأتمتة 80% من محادثات عملائك",
    ctaEn: "Download Free Guide",
    ctaAr: "تحميل الدليل المجاني",
    placeholderNameEn: "Your name",
    placeholderNameAr: "اسمك",
    placeholderEmailEn: "Email address",
    placeholderEmailAr: "البريد الإلكتروني",
    placeholderCompanyEn: "Company (optional)",
    placeholderCompanyAr: "الشركة (اختياري)",
    color: "blue",
  },
  discount: {
    icon: Gift,
    titleEn: "Wait! Get 20% Off Your First Month",
    titleAr: "انتظر! احصل على خصم 20% على الشهر الأول",
    subtitleEn: "Start automating your WhatsApp conversations today",
    subtitleAr: "ابدأ في أتمتة محادثات الواتساب الخاصة بك اليوم",
    ctaEn: "Claim Your Discount",
    ctaAr: "احصل على الخصم",
    placeholderNameEn: "Your name",
    placeholderNameAr: "اسمك",
    placeholderEmailEn: "Email address",
    placeholderEmailAr: "البريد الإلكتروني",
    placeholderCompanyEn: "Company (optional)",
    placeholderCompanyAr: "الشركة (اختياري)",
    color: "green",
  },
  newsletter: {
    icon: TrendingUp,
    titleEn: "Don't Miss Our Latest Tips & Insights",
    titleAr: "لا تفوت أحدث النصائح والأفكار",
    subtitleEn: "Join 5,000+ businesses automating their customer service",
    subtitleAr: "انضم إلى أكثر من 5,000 شركة تقوم بأتمتة خدمة العملاء",
    ctaEn: "Subscribe Now",
    ctaAr: "اشترك الآن",
    placeholderNameEn: "Your name",
    placeholderNameAr: "اسمك",
    placeholderEmailEn: "Email address",
    placeholderEmailAr: "البريد الإلكتروني",
    placeholderCompanyEn: "Company (optional)",
    placeholderCompanyAr: "الشركة (اختياري)",
    color: "purple",
  },
  demo: {
    icon: CheckCircle,
    titleEn: "See Mawidi in Action - Book a Free Demo",
    titleAr: "شاهد مويدي عمليًا - احجز عرضًا تجريبيًا مجانيًا",
    subtitleEn: "Get a personalized walkthrough of our platform",
    subtitleAr: "احصل على جولة مخصصة لمنصتنا",
    ctaEn: "Schedule Demo",
    ctaAr: "جدولة عرض توضيحي",
    placeholderNameEn: "Your name",
    placeholderNameAr: "اسمك",
    placeholderEmailEn: "Email address",
    placeholderEmailAr: "البريد الإلكتروني",
    placeholderCompanyEn: "Company (optional)",
    placeholderCompanyAr: "الشركة (اختياري)",
    color: "indigo",
  },
};

type ColorKey = "blue" | "green" | "purple" | "indigo";

const COLOR_CLASSES: Record<
  ColorKey,
  { gradient: string; hover: string; icon: string; ring: string }
> = {
  blue: {
    gradient: "from-blue-500 to-blue-600",
    hover: "hover:from-blue-600 hover:to-blue-700",
    icon: "text-blue-500",
    ring: "focus:ring-blue-500",
  },
  green: {
    gradient: "from-green-500 to-green-600",
    hover: "hover:from-green-600 hover:to-green-700",
    icon: "text-green-500",
    ring: "focus:ring-green-500",
  },
  purple: {
    gradient: "from-purple-500 to-purple-600",
    hover: "hover:from-purple-600 hover:to-purple-700",
    icon: "text-purple-500",
    ring: "focus:ring-purple-500",
  },
  indigo: {
    gradient: "from-indigo-500 to-indigo-600",
    hover: "hover:from-indigo-600 hover:to-indigo-700",
    icon: "text-indigo-500",
    ring: "focus:ring-indigo-500",
  },
};

/**
 * ExitIntentPopup Component
 *
 * A conversion-optimized popup that appears when users show exit intent.
 * Includes 4 variants: guide download, discount offer, newsletter, demo booking
 *
 * Features:
 * - Exit intent detection with cookie persistence
 * - 4 pre-configured variants with different value propositions
 * - Bilingual support (Arabic/English)
 * - Email validation
 * - Loading and success states
 * - Accessible and responsive design
 *
 * @example
 * <ExitIntentPopup
 *   variant="guide"
 *   language="en"
 *   enabled={true}
 *   cookieDays={7}
 *   onSubmit={async (data) => {
 *     await fetch('/api/leads/capture', { method: 'POST', body: JSON.stringify(data) });
 *   }}
 * />
 */
export function ExitIntentPopup({
  variant = "guide",
  language = "en",
  onSubmit,
  onClose,
  enabled = true,
  cookieDays = 7,
}: ExitIntentPopupProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isSuccess, setIsSuccess] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    company: "",
  });

  const config = VARIANT_CONFIG[variant];
  const colors = COLOR_CLASSES[config.color as ColorKey];
  const isRTL = language === "ar";

  useExitIntent({
    enabled,
    threshold: 50,
    delay: 300,
    cookieDays,
    cookieName: `mawidi_exit_intent_${variant}`,
    onTrigger: () => setIsOpen(true),
  });

  // Handle form input changes
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFormData((prev) => ({
      ...prev,
      [e.target.name]: e.target.value,
    }));
    setError(null);
  };

  // Validate email
  const isValidEmail = (email: string): boolean => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  };

  // Handle form submission
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    // Validation
    if (!formData.name.trim()) {
      setError(isRTL ? "الرجاء إدخال اسمك" : "Please enter your name");
      return;
    }

    if (!formData.email.trim()) {
      setError(
        isRTL ? "الرجاء إدخال بريدك الإلكتروني" : "Please enter your email",
      );
      return;
    }

    if (!isValidEmail(formData.email)) {
      setError(isRTL ? "البريد الإلكتروني غير صحيح" : "Invalid email address");
      return;
    }

    setIsSubmitting(true);

    try {
      const leadData: LeadData = {
        name: formData.name,
        email: formData.email,
        company: formData.company || undefined,
        variant,
        language,
      };

      // Call the provided onSubmit handler or default API
      if (onSubmit) {
        await onSubmit(leadData);
      } else {
        const response = await fetch("/api/leads/capture", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(leadData),
        });

        if (!response.ok) {
          const errorData = await response.json();
          throw new Error(errorData.error || "Failed to submit");
        }
      }

      setIsSuccess(true);

      // Close popup after 2 seconds
      setTimeout(() => {
        handleClose();
      }, 2000);
    } catch (err) {
      setError(
        isRTL
          ? "حدث خطأ. يرجى المحاولة مرة أخرى."
          : "Something went wrong. Please try again.",
      );
      console.error("Exit intent popup submission error:", err);
    } finally {
      setIsSubmitting(false);
    }
  };

  // Handle close
  const handleClose = () => {
    setIsOpen(false);
    setIsSuccess(false);
    setFormData({ name: "", email: "", company: "" });
    setError(null);
    onClose?.();
  };

  // Don't render if not open
  if (!isOpen) return null;

  const IconComponent = config.icon;

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4"
      role="dialog"
      aria-modal="true"
      aria-labelledby="exit-intent-title"
      dir={isRTL ? "rtl" : "ltr"}
    >
      <div className="relative w-full max-w-md bg-white rounded-2xl shadow-2xl overflow-hidden animate-in fade-in zoom-in duration-300">
        {/* Close button */}
        <button
          onClick={handleClose}
          className={`absolute top-4 ${
            isRTL ? "left-4" : "right-4"
          } z-10 p-2 text-gray-400 hover:text-gray-600 transition-colors rounded-full hover:bg-gray-100`}
          aria-label={isRTL ? "إغلاق" : "Close"}
        >
          <X className="w-5 h-5" />
        </button>

        {/* Success state */}
        {isSuccess ? (
          <div className="p-8 text-center">
            <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-green-100 flex items-center justify-center">
              <CheckCircle className="w-10 h-10 text-green-500" />
            </div>
            <h3 className="text-2xl font-bold text-gray-900 mb-2">
              {isRTL ? "شكرًا لك!" : "Thank You!"}
            </h3>
            <p className="text-gray-600">
              {isRTL ? "سنتواصل معك قريبًا" : "We'll be in touch soon"}
            </p>
          </div>
        ) : (
          <>
            {/* Icon header */}
            <div
              className={`bg-gradient-to-r ${colors.gradient} p-6 text-white`}
            >
              <div className="flex items-center justify-center mb-4">
                <div className="w-12 h-12 bg-white/20 rounded-full flex items-center justify-center backdrop-blur-sm">
                  <IconComponent className="w-6 h-6" />
                </div>
              </div>
              <h2
                id="exit-intent-title"
                className="text-2xl font-bold text-center mb-2"
              >
                {isRTL ? config.titleAr : config.titleEn}
              </h2>
              <p className="text-center text-white/90">
                {isRTL ? config.subtitleAr : config.subtitleEn}
              </p>
            </div>

            {/* Form */}
            <form onSubmit={handleSubmit} className="p-6 space-y-4">
              {/* Name input */}
              <div>
                <label
                  htmlFor="name"
                  className="block text-sm font-medium text-gray-700 mb-1"
                >
                  {isRTL ? "الاسم" : "Name"}
                </label>
                <input
                  type="text"
                  id="name"
                  name="name"
                  value={formData.name}
                  onChange={handleChange}
                  className={`w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 ${colors.ring} focus:border-transparent transition-colors`}
                  placeholder={
                    isRTL ? config.placeholderNameAr : config.placeholderNameEn
                  }
                  required
                  disabled={isSubmitting}
                />
              </div>

              {/* Email input */}
              <div>
                <label
                  htmlFor="email"
                  className="block text-sm font-medium text-gray-700 mb-1"
                >
                  {isRTL ? "البريد الإلكتروني" : "Email"}
                </label>
                <input
                  type="email"
                  id="email"
                  name="email"
                  value={formData.email}
                  onChange={handleChange}
                  className={`w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 ${colors.ring} focus:border-transparent transition-colors`}
                  placeholder={
                    isRTL
                      ? config.placeholderEmailAr
                      : config.placeholderEmailEn
                  }
                  required
                  disabled={isSubmitting}
                />
              </div>

              {/* Company input (optional) */}
              <div>
                <label
                  htmlFor="company"
                  className="block text-sm font-medium text-gray-700 mb-1"
                >
                  {isRTL ? "الشركة (اختياري)" : "Company (optional)"}
                </label>
                <input
                  type="text"
                  id="company"
                  name="company"
                  value={formData.company}
                  onChange={handleChange}
                  className={`w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 ${colors.ring} focus:border-transparent transition-colors`}
                  placeholder={
                    isRTL
                      ? config.placeholderCompanyAr
                      : config.placeholderCompanyEn
                  }
                  disabled={isSubmitting}
                />
              </div>

              {/* Error message */}
              {error && (
                <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
                  {error}
                </div>
              )}

              {/* Submit button */}
              <button
                type="submit"
                disabled={isSubmitting}
                className={`w-full py-3 px-6 bg-gradient-to-r ${colors.gradient} ${colors.hover} text-white font-semibold rounded-lg shadow-lg transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed`}
              >
                {isSubmitting
                  ? isRTL
                    ? "جاري الإرسال..."
                    : "Submitting..."
                  : isRTL
                    ? config.ctaAr
                    : config.ctaEn}
              </button>

              {/* Privacy note */}
              <p className="text-xs text-gray-500 text-center">
                {isRTL
                  ? "نحن نحترم خصوصيتك. لن نشارك معلوماتك أبدًا."
                  : "We respect your privacy. We will never share your information."}
              </p>
            </form>
          </>
        )}
      </div>
    </div>
  );
}
