"use client";

import React, { useState } from "react";
import { ExitIntentPopup, PopupVariant, LeadData } from "./ExitIntentPopup";
import {
  Download,
  Gift,
  TrendingUp,
  CheckCircle,
  RotateCcw,
} from "lucide-react";

interface ExitIntentDemoProps {
  language: "ar" | "en";
}

const VARIANTS: {
  id: PopupVariant;
  label: string;
  labelAr: string;
  icon: React.ElementType;
  color: string;
}[] = [
  {
    id: "guide",
    label: "Free Guide Download",
    labelAr: "تحميل دليل مجاني",
    icon: Download,
    color: "blue",
  },
  {
    id: "discount",
    label: "20% Discount Offer",
    labelAr: "خصم 20%",
    icon: Gift,
    color: "green",
  },
  {
    id: "newsletter",
    label: "Newsletter Signup",
    labelAr: "الاشتراك في النشرة",
    icon: TrendingUp,
    color: "purple",
  },
  {
    id: "demo",
    label: "Book a Demo",
    labelAr: "حجز عرض توضيحي",
    icon: CheckCircle,
    color: "indigo",
  },
];

/**
 * ExitIntentDemo Component
 *
 * Demo page for testing all 4 exit intent popup variants.
 * Allows triggering popups manually and resetting cookies for testing.
 */
export function ExitIntentDemo({ language }: ExitIntentDemoProps) {
  const [activeVariant, setActiveVariant] = useState<PopupVariant | null>(null);
  const [showPopup, setShowPopup] = useState(false);
  const [submissions, setSubmissions] = useState<LeadData[]>([]);
  const isRTL = language === "ar";

  const handleTrigger = (variant: PopupVariant) => {
    setActiveVariant(variant);
    setShowPopup(true);
  };

  const handleSubmit = async (data: LeadData) => {
    console.log("Exit intent lead submitted:", data);
    setSubmissions((prev) => [data, ...prev]);

    // In production, this would call the real API
    // For demo, we just simulate success
    await new Promise((resolve) => setTimeout(resolve, 1000));
  };

  const handleClose = () => {
    setShowPopup(false);
    setActiveVariant(null);
  };

  const resetCookies = () => {
    // Clear all exit intent cookies
    VARIANTS.forEach((variant) => {
      document.cookie = `mawidi_exit_intent_${variant.id}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/;SameSite=Lax`;
    });
    alert(isRTL ? "تم مسح جميع ملفات تعريف الارتباط" : "All cookies cleared");
  };

  return (
    <div
      className={`min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 py-12 px-4 sm:px-6 lg:px-8 ${isRTL ? "rtl" : "ltr"}`}
    >
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="text-center mb-12">
          <h1 className="text-4xl font-bold text-gray-900 mb-4">
            {isRTL ? "عرض توضيحي لنافذة نية الخروج" : "Exit Intent Popup Demo"}
          </h1>
          <p className="text-lg text-gray-600 mb-6">
            {isRTL
              ? "اختبر جميع المتغيرات الأربعة للنافذة المنبثقة لنية الخروج"
              : "Test all 4 exit intent popup variants"}
          </p>
          <button
            onClick={resetCookies}
            className="inline-flex items-center gap-2 px-4 py-2 bg-white border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors"
          >
            <RotateCcw className="w-4 h-4" />
            {isRTL ? "إعادة تعيين ملفات تعريف الارتباط" : "Reset Cookies"}
          </button>
        </div>

        {/* Variant Grid */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-12">
          {VARIANTS.map((variant) => {
            const Icon = variant.icon;
            return (
              <button
                key={variant.id}
                onClick={() => handleTrigger(variant.id)}
                className={`group relative overflow-hidden bg-white rounded-2xl shadow-lg hover:shadow-2xl transition-all duration-300 p-6 text-${isRTL ? "right" : "left"}`}
              >
                <div
                  className={`absolute inset-0 bg-gradient-to-br from-${variant.color}-400 to-${variant.color}-600 opacity-0 group-hover:opacity-10 transition-opacity`}
                />
                <div className="relative">
                  <div
                    className={`w-12 h-12 rounded-full bg-${variant.color}-100 flex items-center justify-center mb-4`}
                  >
                    <Icon className={`w-6 h-6 text-${variant.color}-600`} />
                  </div>
                  <h3 className="text-xl font-bold text-gray-900 mb-2">
                    {isRTL ? variant.labelAr : variant.label}
                  </h3>
                  <p className="text-sm text-gray-600">
                    {isRTL ? "انقر للتشغيل" : "Click to trigger"}
                  </p>
                </div>
              </button>
            );
          })}
        </div>

        {/* Instructions */}
        <div className="bg-white rounded-2xl shadow-lg p-8 mb-8">
          <h2 className="text-2xl font-bold text-gray-900 mb-4">
            {isRTL ? "كيفية الاختبار" : "How to Test"}
          </h2>
          <ul
            className={`space-y-3 text-gray-600 ${isRTL ? "mr-6" : "ml-6"} list-disc`}
          >
            <li>
              {isRTL
                ? "انقر فوق أي متغير أعلاه لتشغيل النافذة المنبثقة يدويًا"
                : "Click any variant above to trigger the popup manually"}
            </li>
            <li>
              {isRTL
                ? "حرك الماوس نحو أعلى الصفحة للتشغيل التلقائي"
                : "Move your mouse towards the top of the page for automatic trigger"}
            </li>
            <li>
              {isRTL
                ? "سيتم حفظ كل متغير في ملف تعريف ارتباط منفصل لمدة 7 أيام"
                : "Each variant saves a separate cookie for 7 days"}
            </li>
            <li>
              {isRTL
                ? 'استخدم زر "إعادة تعيين ملفات تعريف الارتباط" لمسح جميع ملفات تعريف الارتباط'
                : 'Use "Reset Cookies" button to clear all cookies'}
            </li>
            <li>
              {isRTL
                ? "في الإنتاج، سيتم إرسال العملاء المحتملين إلى /api/leads/capture"
                : "In production, leads will be sent to /api/leads/capture"}
            </li>
          </ul>
        </div>

        {/* Submissions Log */}
        {submissions.length > 0 && (
          <div className="bg-white rounded-2xl shadow-lg p-8">
            <h2 className="text-2xl font-bold text-gray-900 mb-4">
              {isRTL
                ? "السجل (وضع العرض التوضيحي)"
                : "Submission Log (Demo Mode)"}
            </h2>
            <div className="space-y-4">
              {submissions.map((submission, index) => (
                <div
                  key={index}
                  className="border border-gray-200 rounded-lg p-4 bg-gray-50"
                >
                  <div className="flex items-center justify-between mb-2">
                    <span className="font-semibold text-gray-900">
                      {submission.name}
                    </span>
                    <span className="text-sm text-gray-500 capitalize">
                      {submission.variant}
                    </span>
                  </div>
                  <p className="text-sm text-gray-600">{submission.email}</p>
                  {submission.company && (
                    <p className="text-sm text-gray-600">
                      {submission.company}
                    </p>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Feature Details */}
        <div className="mt-12 grid grid-cols-1 md:grid-cols-3 gap-6">
          <div className="bg-white rounded-xl p-6 shadow-md">
            <h3 className="font-bold text-gray-900 mb-2">
              {isRTL ? "اكتشاف نية الخروج" : "Exit Intent Detection"}
            </h3>
            <p className="text-sm text-gray-600">
              {isRTL
                ? "يتتبع حركة الماوس ويتم التشغيل عندما ينتقل المستخدم إلى أعلى الصفحة"
                : "Tracks mouse movement and triggers when user moves towards top of page"}
            </p>
          </div>
          <div className="bg-white rounded-xl p-6 shadow-md">
            <h3 className="font-bold text-gray-900 mb-2">
              {isRTL ? "استمرارية ملفات تعريف الارتباط" : "Cookie Persistence"}
            </h3>
            <p className="text-sm text-gray-600">
              {isRTL
                ? "تذكر المستخدمين لمدة 7 أيام لتجنب الإزعاج"
                : "Remembers users for 7 days to avoid annoying repeat visitors"}
            </p>
          </div>
          <div className="bg-white rounded-xl p-6 shadow-md">
            <h3 className="font-bold text-gray-900 mb-2">
              {isRTL ? "دعم متعدد اللغات" : "Multilingual Support"}
            </h3>
            <p className="text-sm text-gray-600">
              {isRTL
                ? "دعم كامل للعربية والإنجليزية مع RTL"
                : "Full Arabic and English support with RTL"}
            </p>
          </div>
        </div>
      </div>

      {/* Active Popup */}
      {showPopup && activeVariant && (
        <ExitIntentPopup
          variant={activeVariant}
          language={language}
          enabled={true}
          cookieDays={7}
          onSubmit={handleSubmit}
          onClose={handleClose}
        />
      )}
    </div>
  );
}
