"use client";

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

interface LeadGateModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
  lang: Lang;
  resourceTitle: string;
  resourceType?: "guide" | "case-study" | "whitepaper" | "template";
}

const content = {
  en: {
    title: "Get Your Free Resource",
    subtitle: "Fill in your details to download",
    namePlaceholder: "Full Name",
    emailPlaceholder: "Work Email",
    companyPlaceholder: "Company Name (optional)",
    submitButton: "Download Now",
    submitting: "Processing...",
    privacyNote: "We respect your privacy. Your data is secure.",
    success: "Success! Your download will start shortly.",
    errorGeneric: "Something went wrong. Please try again.",
    errorValidation: "Please fill in all required fields.",
    close: "Close",
  },
  ar: {
    title: "احصل على المورد المجاني",
    subtitle: "أدخل بياناتك للتحميل",
    namePlaceholder: "الاسم الكامل",
    emailPlaceholder: "البريد الإلكتروني للعمل",
    companyPlaceholder: "اسم الشركة (اختياري)",
    submitButton: "تحميل الآن",
    submitting: "جاري المعالجة...",
    privacyNote: "نحترم خصوصيتك. بياناتك آمنة.",
    success: "تم بنجاح! سيبدأ التحميل قريباً.",
    errorGeneric: "حدث خطأ. يرجى المحاولة مرة أخرى.",
    errorValidation: "يرجى ملء جميع الحقول المطلوبة.",
    close: "إغلاق",
  },
};

export default function LeadGateModal({
  isOpen,
  onClose,
  onSuccess,
  lang,
  resourceTitle,
  resourceType = "guide",
}: LeadGateModalProps) {
  const t = content[lang];
  const isAr = lang === "ar";
  const { executeRecaptcha } = useGoogleReCaptcha();

  const [formData, setFormData] = useState({
    name: "",
    email: "",
    company: "",
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  const handleInputChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      const { name, value } = e.target;
      setFormData((prev) => ({ ...prev, [name]: value }));
      setError(null);
    },
    [],
  );

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

    // Basic validation
    if (!formData.name.trim() || !formData.email.trim()) {
      setError(t.errorValidation);
      return;
    }

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

    setIsSubmitting(true);

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

      // Submit to API
      const response = await fetch("/api/leads/resource-download", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          name: formData.name.trim(),
          email: formData.email.trim(),
          company: formData.company.trim() || undefined,
          resourceTitle,
          resourceType,
          language: lang,
          recaptchaToken,
        }),
      });

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.error || "Submission failed");
      }

      // Store unlocked state in localStorage
      const unlockedResources = JSON.parse(
        localStorage.getItem("mawidi_unlocked_resources") || "[]",
      );
      if (!unlockedResources.includes(resourceTitle)) {
        unlockedResources.push(resourceTitle);
        localStorage.setItem(
          "mawidi_unlocked_resources",
          JSON.stringify(unlockedResources),
        );
      }

      // Store lead email for future downloads
      localStorage.setItem("mawidi_lead_email", formData.email);

      setSuccess(true);

      // Trigger success callback after brief delay
      setTimeout(() => {
        onSuccess();
        onClose();
      }, 1500);
    } catch (err) {
      console.error("Lead form error:", err);
      setError(t.errorGeneric);
    } finally {
      setIsSubmitting(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm">
      <div
        className={`relative w-full max-w-md bg-white dark:bg-slate-900 rounded-2xl shadow-2xl transform transition-all ${
          isAr ? "text-right" : "text-left"
        }`}
        dir={isAr ? "rtl" : "ltr"}
      >
        {/* Close button */}
        <button
          onClick={onClose}
          className="absolute top-4 right-4 p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors rounded-full hover:bg-gray-100 dark:hover:bg-slate-800"
          aria-label={t.close}
        >
          <X className="w-5 h-5" />
        </button>

        {/* Content */}
        <div className="p-8">
          {/* Icon */}
          <div className="mb-6 flex justify-center">
            <div className="w-16 h-16 bg-gradient-to-br from-brand-green to-emerald-500 rounded-2xl flex items-center justify-center shadow-lg">
              <Download className="w-8 h-8 text-white" />
            </div>
          </div>

          {/* Title */}
          <h2 className="text-2xl font-bold text-gray-900 dark:text-white text-center mb-2">
            {t.title}
          </h2>
          <p className="text-gray-600 dark:text-gray-400 text-center mb-2">
            {t.subtitle}
          </p>
          <p className="text-sm text-brand-green font-medium text-center mb-6">
            {resourceTitle}
          </p>

          {/* Success State */}
          {success ? (
            <div className="flex flex-col items-center py-8">
              <CheckCircle className="w-16 h-16 text-brand-green mb-4" />
              <p className="text-lg font-medium text-gray-900 dark:text-white text-center">
                {t.success}
              </p>
            </div>
          ) : (
            /* Form */
            <form onSubmit={handleSubmit} className="space-y-4">
              {/* Name */}
              <div>
                <input
                  type="text"
                  name="name"
                  value={formData.name}
                  onChange={handleInputChange}
                  placeholder={t.namePlaceholder}
                  required
                  className="w-full px-4 py-3 border border-gray-200 dark:border-slate-700 rounded-xl bg-gray-50 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"
                />
              </div>

              {/* Email */}
              <div>
                <input
                  type="email"
                  name="email"
                  value={formData.email}
                  onChange={handleInputChange}
                  placeholder={t.emailPlaceholder}
                  required
                  className="w-full px-4 py-3 border border-gray-200 dark:border-slate-700 rounded-xl bg-gray-50 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"
                />
              </div>

              {/* Company */}
              <div>
                <input
                  type="text"
                  name="company"
                  value={formData.company}
                  onChange={handleInputChange}
                  placeholder={t.companyPlaceholder}
                  className="w-full px-4 py-3 border border-gray-200 dark:border-slate-700 rounded-xl bg-gray-50 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"
                />
              </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>
              )}

              {/* Submit button */}
              <button
                type="submit"
                disabled={isSubmitting}
                className="w-full py-3 px-6 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"
              >
                {isSubmitting ? (
                  <>
                    <Loader2 className="w-5 h-5 animate-spin" />
                    {t.submitting}
                  </>
                ) : (
                  <>
                    <Download className="w-5 h-5" />
                    {t.submitButton}
                  </>
                )}
              </button>

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