"use client";

import { useState, useCallback, useEffect, FormEvent } from "react";
import { useGoogleReCaptcha } from "react-google-recaptcha-v3";
import { Mail, Loader2, CheckCircle, AlertCircle } from "lucide-react";
import type { Lang } from "@/lib/config";

// Helper to get CSRF token from cookie
function getCSRFToken(): string | null {
  if (typeof document === "undefined") return null;
  const match = document.cookie.match(/csrf-token=([^;]+)/);
  return match ? decodeURIComponent(match[1]) : null;
}

interface InlineEmailFormProps {
  lang: Lang;
  context: "homepage" | "pricing" | "features";
  className?: string;
}

const content = {
  en: {
    homepage: {
      title: "Start Your Free Trial",
      subtitle: "Join hundreds of businesses automating appointments",
      placeholder: "Enter your work email",
      button: "Get Started",
    },
    pricing: {
      title: "Ready to Get Started?",
      subtitle: "Start your 14-day free trial, no credit card required",
      placeholder: "Enter your work email",
      button: "Start Free Trial",
    },
    features: {
      title: "See Mawidi in Action",
      subtitle: "Get a personalized demo and pricing for your business",
      placeholder: "Enter your work email",
      button: "Request Demo",
    },
    submitting: "Processing...",
    success: "Success! Check your email for next steps.",
    errorGeneric: "Something went wrong. Please try again.",
    errorValidation: "Please enter a valid work email.",
    errorBot: "Verification failed. Please try again.",
    privacyNote: "We respect your privacy. Unsubscribe anytime.",
  },
  ar: {
    homepage: {
      title: "ابدأ تجربتك المجانية",
      subtitle: "انضم لمئات الشركات التي تؤتمت مواعيدها",
      placeholder: "أدخل بريدك الإلكتروني للعمل",
      button: "ابدأ الآن",
    },
    pricing: {
      title: "جاهز للبدء؟",
      subtitle: "ابدأ تجربتك المجانية لمدة 14 يوماً، بدون بطاقة ائتمان",
      placeholder: "أدخل بريدك الإلكتروني للعمل",
      button: "ابدأ التجربة المجانية",
    },
    features: {
      title: "شاهد موعدي في العمل",
      subtitle: "احصل على عرض تجريبي مخصص وأسعار لعملك",
      placeholder: "أدخل بريدك الإلكتروني للعمل",
      button: "اطلب عرض تجريبي",
    },
    submitting: "جاري المعالجة...",
    success: "تم بنجاح! تحقق من بريدك الإلكتروني للخطوات التالية.",
    errorGeneric: "حدث خطأ. يرجى المحاولة مرة أخرى.",
    errorValidation: "يرجى إدخال بريد إلكتروني صالح للعمل.",
    errorBot: "فشل التحقق. يرجى المحاولة مرة أخرى.",
    privacyNote: "نحترم خصوصيتك. إلغاء الاشتراك في أي وقت.",
  },
};

export default function InlineEmailForm({
  lang,
  context,
  className = "",
}: InlineEmailFormProps) {
  const t = content[lang];
  const contextContent = t[context];
  const isAr = lang === "ar";
  const { executeRecaptcha } = useGoogleReCaptcha();

  const [email, setEmail] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  // Initialize CSRF token on mount
  useEffect(() => {
    fetch("/api/csrf").catch(() => {});
  }, []);

  const handleSubmit = useCallback(
    async (e: FormEvent<HTMLFormElement>) => {
      e.preventDefault();
      setError(null);

      // Basic validation
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!email.trim() || !emailRegex.test(email)) {
        setError(t.errorValidation);
        return;
      }

      setIsSubmitting(true);

      try {
        // Get reCAPTCHA token
        let recaptchaToken = "";
        if (executeRecaptcha) {
          recaptchaToken = await executeRecaptcha("inline_email_form");
        }

        // Map context to resource type and title
        const resourceMapping = {
          homepage: {
            type: "guide" as const,
            title: isAr
              ? "الصفحة الرئيسية - نموذج البريد الإلكتروني"
              : "Homepage - Email Form",
          },
          pricing: {
            type: "guide" as const,
            title: isAr ? "التسعير - تجربة مجانية" : "Pricing - Free Trial",
          },
          features: {
            type: "guide" as const,
            title: isAr
              ? "المزايا - طلب عرض تجريبي"
              : "Features - Demo Request",
          },
        };

        const resourceInfo = resourceMapping[context];

        // Submit to Lead API
        const csrfToken = getCSRFToken();
        const response = await fetch("/api/leads/resource-download", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            ...(csrfToken && { "x-csrf-token": csrfToken }),
          },
          body: JSON.stringify({
            name: email.split("@")[0], // Extract name from email prefix
            email: email.trim(),
            company: undefined,
            resourceTitle: resourceInfo.title,
            resourceType: resourceInfo.type,
            language: lang,
            recaptchaToken,
          }),
        });

        if (!response.ok) {
          const data = await response.json();
          if (data.error && data.error.includes("Bot verification")) {
            throw new Error(t.errorBot);
          }
          throw new Error(data.error || "Submission failed");
        }

        // Success state
        setSuccess(true);
        setEmail("");

        // Reset success message after 5 seconds
        setTimeout(() => {
          setSuccess(false);
        }, 5000);
      } catch (err) {
        console.error("Inline form error:", err);
        setError(err instanceof Error ? err.message : t.errorGeneric);
      } finally {
        setIsSubmitting(false);
      }
    },
    [email, executeRecaptcha, context, lang, isAr, t],
  );

  return (
    <div
      className={`rounded-2xl bg-gradient-to-br from-brand-green/10 to-emerald-500/10 p-8 border border-brand-green/20 ${className}`}
      dir={isAr ? "rtl" : "ltr"}
    >
      {/* Title */}
      <div className={`mb-6 ${isAr ? "text-right" : "text-left"}`}>
        <h3 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
          {contextContent.title}
        </h3>
        <p className="text-gray-600 dark:text-gray-400">
          {contextContent.subtitle}
        </p>
      </div>

      {/* Success State */}
      {success ? (
        <div className="flex items-center gap-3 p-4 bg-green-50 dark:bg-green-900/20 rounded-xl border border-green-200 dark:border-green-800">
          <CheckCircle className="w-6 h-6 text-green-600 dark:text-green-400 flex-shrink-0" />
          <p className="text-green-800 dark:text-green-200 font-medium">
            {t.success}
          </p>
        </div>
      ) : (
        /* Form */
        <form onSubmit={handleSubmit} className="space-y-4">
          {/* Email Input with Button */}
          <div className="flex flex-col sm:flex-row gap-3">
            <div className="flex-1 relative">
              <Mail
                className={`absolute top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 ${
                  isAr ? "right-3" : "left-3"
                }`}
              />
              <input
                type="email"
                aria-label={isAr ? "عنوان البريد الإلكتروني" : "Email address"}
                value={email}
                onChange={(e) => {
                  setEmail(e.target.value);
                  setError(null);
                }}
                placeholder={contextContent.placeholder}
                required
                disabled={isSubmitting}
                className={`w-full ${
                  isAr ? "pr-10 pl-4" : "pl-10 pr-4"
                } py-3 border border-gray-200 dark:border-slate-700 rounded-xl bg-white dark:bg-slate-800 text-gray-900 dark:text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-brand-green focus:border-transparent transition-all disabled:opacity-50 disabled:cursor-not-allowed`}
              />
            </div>
            <button
              type="submit"
              disabled={isSubmitting}
              className="px-6 py-3 bg-gradient-to-r from-brand-green to-emerald-500 text-white font-semibold rounded-xl hover:from-green-600 hover:to-emerald-600 focus:outline-none focus:ring-2 focus:ring-brand-green focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-all flex items-center justify-center gap-2 whitespace-nowrap"
            >
              {isSubmitting ? (
                <>
                  <Loader2 className="w-5 h-5 animate-spin" />
                  <span>{t.submitting}</span>
                </>
              ) : (
                <span>{contextContent.button}</span>
              )}
            </button>
          </div>

          {/* Error message */}
          {error && (
            <div className="flex items-center gap-2 text-red-600 dark:text-red-400 text-sm p-3 bg-red-50 dark:bg-red-900/20 rounded-lg">
              <AlertCircle className="w-4 h-4 flex-shrink-0" />
              <span>{error}</span>
            </div>
          )}

          {/* Privacy note */}
          <p className="text-xs text-gray-500 dark:text-gray-400 text-center">
            {t.privacyNote}
          </p>
        </form>
      )}
    </div>
  );
}
