"use client";

import { useState, useEffect } from "react";
import { Lang } from "@/lib/config";

interface LeadGateModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSubmit: (data: LeadFormData) => Promise<void>;
  resourceTitle: string;
  resourceType:
    | "guide"
    | "case-study"
    | "whitepaper"
    | "template"
    | "calculator";
  lang: Lang;
}

export interface LeadFormData {
  name: string;
  email: string;
  company?: string;
  resourceTitle: string;
  resourceType: string;
  language: Lang;
}

export default function LeadGateModal({
  isOpen,
  onClose,
  onSubmit,
  resourceTitle,
  resourceType,
  lang,
}: LeadGateModalProps) {
  const isAr = lang === "ar";
  const [formData, setFormData] = useState<LeadFormData>({
    name: "",
    email: "",
    company: "",
    resourceTitle,
    resourceType,
    language: lang,
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState("");
  const [csrfToken, setCsrfToken] = useState("");

  // Fetch CSRF token when modal opens
  useEffect(() => {
    if (isOpen && !csrfToken) {
      fetch("/api/csrf")
        .then((res) => res.json())
        .then((data) => setCsrfToken(data.csrfToken))
        .catch(() => {
          setError(
            isAr
              ? "فشل التحميل. يرجى المحاولة مرة أخرى."
              : "Failed to load. Please try again.",
          );
        });
    }
  }, [isOpen, csrfToken, isAr]);

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

    try {
      if (!csrfToken) {
        throw new Error("CSRF token not available");
      }
      await onSubmit(formData);
    } catch {
      setError(
        isAr
          ? "حدث خطأ. يرجى المحاولة مرة أخرى."
          : "An error occurred. Please try again.",
      );
    } finally {
      setIsSubmitting(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4">
      <div
        className="bg-white dark:bg-slate-800 rounded-2xl max-w-lg w-full shadow-2xl"
        dir={isAr ? "rtl" : "ltr"}
      >
        {/* Header */}
        <div className="p-6 border-b border-slate-200 dark:border-slate-700 flex items-start justify-between">
          <div>
            <div className="flex items-center gap-2 mb-2">
              <svg
                className="w-5 h-5 text-brand-green"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"
                />
              </svg>
              <span className="text-sm font-medium text-brand-green">
                {isAr ? "محتوى حصري" : "Exclusive Content"}
              </span>
            </div>
            <h2 className="text-2xl font-bold text-slate-900 dark:text-white">
              {isAr ? "الوصول إلى المورد" : "Access Resource"}
            </h2>
            <p className="text-sm text-slate-600 dark:text-slate-400 mt-2">
              {isAr
                ? "أدخل تفاصيلك للوصول الفوري إلى هذا المورد المجاني"
                : "Enter your details for instant access to this free resource"}
            </p>
          </div>
          <button
            onClick={onClose}
            className="text-slate-400 hover:text-slate-600 dark:hover:text-slate-300 transition-colors"
            aria-label={isAr ? "إغلاق" : "Close"}
          >
            <svg
              className="w-6 h-6"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
          </button>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} className="p-6">
          <div className="space-y-4">
            {/* Name */}
            <div>
              <label
                htmlFor="name"
                className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2"
              >
                {isAr ? "الاسم الكامل" : "Full Name"}{" "}
                <span className="text-red-500">*</span>
              </label>
              <input
                type="text"
                id="name"
                required
                value={formData.name}
                onChange={(e) =>
                  setFormData({ ...formData, name: e.target.value })
                }
                className="w-full px-4 py-3 border border-slate-300 dark:border-slate-600 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-transparent dark:bg-slate-700 dark:text-white"
                placeholder={isAr ? "أدخل اسمك الكامل" : "Enter your full name"}
              />
            </div>

            {/* Email */}
            <div>
              <label
                htmlFor="email"
                className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2"
              >
                {isAr ? "البريد الإلكتروني" : "Email"}{" "}
                <span className="text-red-500">*</span>
              </label>
              <input
                type="email"
                id="email"
                required
                value={formData.email}
                onChange={(e) =>
                  setFormData({ ...formData, email: e.target.value })
                }
                className="w-full px-4 py-3 border border-slate-300 dark:border-slate-600 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-transparent dark:bg-slate-700 dark:text-white"
                placeholder={isAr ? "you@company.com" : "you@company.com"}
                dir="ltr"
              />
            </div>

            {/* Company (Optional) */}
            <div>
              <label
                htmlFor="company"
                className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2"
              >
                {isAr ? "الشركة" : "Company"} ({isAr ? "اختياري" : "Optional"})
              </label>
              <input
                type="text"
                id="company"
                value={formData.company}
                onChange={(e) =>
                  setFormData({ ...formData, company: e.target.value })
                }
                className="w-full px-4 py-3 border border-slate-300 dark:border-slate-600 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-transparent dark:bg-slate-700 dark:text-white"
                placeholder={isAr ? "اسم شركتك" : "Your company name"}
              />
            </div>

            {/* Error Message */}
            {error && (
              <div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg text-red-700 dark:text-red-400 text-sm">
                {error}
              </div>
            )}

            {/* Privacy Notice */}
            <p className="text-xs text-slate-500 dark:text-slate-400">
              {isAr
                ? "نحن نحترم خصوصيتك. لن نشارك معلوماتك أبدًا مع أطراف ثالثة."
                : "We respect your privacy. We will never share your information with third parties."}
            </p>
          </div>

          {/* Actions */}
          <div className="mt-6 flex gap-3">
            <button
              type="button"
              onClick={onClose}
              className="flex-1 px-6 py-3 border border-slate-300 dark:border-slate-600 text-slate-700 dark:text-slate-300 rounded-lg hover:bg-slate-50 dark:hover:bg-slate-700 transition-colors font-medium"
            >
              {isAr ? "إلغاء" : "Cancel"}
            </button>
            <button
              type="submit"
              disabled={isSubmitting}
              className="flex-1 px-6 py-3 bg-brand-green text-white rounded-lg hover:bg-brand-green-dark transition-colors font-medium disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
            >
              {isSubmitting ? (
                <>
                  <svg
                    className="animate-spin h-5 w-5"
                    fill="none"
                    viewBox="0 0 24 24"
                  >
                    <circle
                      className="opacity-25"
                      cx="12"
                      cy="12"
                      r="10"
                      stroke="currentColor"
                      strokeWidth="4"
                    />
                    <path
                      className="opacity-75"
                      fill="currentColor"
                      d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                    />
                  </svg>
                  {isAr ? "جارٍ الإرسال..." : "Submitting..."}
                </>
              ) : (
                <>
                  <svg
                    className="w-5 h-5"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M8 11V7a4 4 0 118 0m-4 8v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2z"
                    />
                  </svg>
                  {isAr ? "فتح المورد" : "Unlock Resource"}
                </>
              )}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
