"use client";

import { useState, useCallback, useEffect } from "react";
import { Lock, Download, FileText, Video, BookOpen } from "lucide-react";
import type { Lang } from "@/lib/config";
import RecaptchaWrapper from "@/components/contact/RecaptchaWrapper";
import LeadGateModal from "./LeadGateModal";

interface LeadGatedResourceProps {
  lang: Lang;
  title: string;
  description?: string;
  resourceType:
    | "guide"
    | "case-study"
    | "whitepaper"
    | "template"
    | "video"
    | "webinar";
  downloadUrl?: string;
  onUnlock?: () => void;
  className?: string;
  children?: React.ReactNode;
}

const resourceIcons = {
  guide: BookOpen,
  "case-study": FileText,
  whitepaper: FileText,
  template: FileText,
  video: Video,
  webinar: Video,
};

const content = {
  en: {
    unlockToAccess: "Unlock to access",
    download: "Download",
    accessNow: "Access Now",
    freeResource: "Free Resource",
  },
  ar: {
    unlockToAccess: "افتح للوصول",
    download: "تحميل",
    accessNow: "الوصول الآن",
    freeResource: "مورد مجاني",
  },
};

export default function LeadGatedResource({
  lang,
  title,
  description,
  resourceType,
  downloadUrl,
  onUnlock,
  className = "",
  children,
}: LeadGatedResourceProps) {
  const t = content[lang];
  const isAr = lang === "ar";
  const [isUnlocked, setIsUnlocked] = useState(false);
  const [showModal, setShowModal] = useState(false);
  const [isChecking, setIsChecking] = useState(true);

  const Icon = resourceIcons[resourceType] || FileText;

  // Check if resource is already unlocked
  useEffect(() => {
    const checkUnlocked = () => {
      try {
        const unlockedResources = JSON.parse(
          localStorage.getItem("mawidi_unlocked_resources") || "[]",
        );
        const leadEmail = localStorage.getItem("mawidi_lead_email");

        // Resource is unlocked if it's in the list or user has provided email before
        if (unlockedResources.includes(title) || leadEmail) {
          setIsUnlocked(true);
        }
      } catch (e) {
        // localStorage might not be available
        console.warn("Could not check unlock status:", e);
      }
      setIsChecking(false);
    };

    checkUnlocked();
  }, [title]);

  const handleClick = useCallback(() => {
    if (isUnlocked) {
      // Already unlocked, trigger download or callback
      if (downloadUrl) {
        window.open(downloadUrl, "_blank");
      }
      onUnlock?.();
    } else {
      // Show lead gate modal
      setShowModal(true);
    }
  }, [isUnlocked, downloadUrl, onUnlock]);

  const handleSuccess = useCallback(() => {
    setIsUnlocked(true);
    onUnlock?.();

    // Trigger download if URL provided
    if (downloadUrl) {
      setTimeout(() => {
        window.open(downloadUrl, "_blank");
      }, 500);
    }
  }, [downloadUrl, onUnlock]);

  const handleCloseModal = useCallback(() => {
    setShowModal(false);
  }, []);

  if (isChecking) {
    return (
      <div
        className={`animate-pulse bg-gray-100 dark:bg-slate-800 rounded-xl h-32 ${className}`}
      />
    );
  }

  // If children provided, wrap them with the gate
  if (children) {
    return (
      <>
        <div
          className={`relative cursor-pointer ${className}`}
          onClick={handleClick}
        >
          {!isUnlocked && (
            <div className="absolute inset-0 bg-gradient-to-t from-white via-white/80 to-transparent dark:from-slate-900 dark:via-slate-900/80 z-10 flex items-end justify-center pb-8 rounded-xl">
              <button className="flex items-center gap-2 px-6 py-3 bg-brand-green text-white font-semibold rounded-xl hover:bg-green-600 transition-all shadow-lg">
                <Lock className="w-5 h-5" />
                {t.unlockToAccess}
              </button>
            </div>
          )}
          {children}
        </div>

        <RecaptchaWrapper>
          <LeadGateModal
            isOpen={showModal}
            onClose={handleCloseModal}
            onSuccess={handleSuccess}
            lang={lang}
            resourceTitle={title}
            resourceType={
              resourceType === "video" || resourceType === "webinar"
                ? "guide"
                : resourceType
            }
          />
        </RecaptchaWrapper>
      </>
    );
  }

  // Default card view
  return (
    <>
      <div
        className={`group relative bg-white dark:bg-slate-800 border border-gray-200 dark:border-slate-700 rounded-xl p-6 hover:shadow-lg transition-all cursor-pointer ${className}`}
        onClick={handleClick}
        dir={isAr ? "rtl" : "ltr"}
      >
        {/* Badge */}
        <div className="absolute top-4 right-4">
          <span className="inline-flex items-center gap-1 px-2 py-1 bg-brand-green/10 text-brand-green text-xs font-medium rounded-full">
            {t.freeResource}
          </span>
        </div>

        {/* Icon */}
        <div
          className={`w-12 h-12 rounded-xl flex items-center justify-center mb-4 ${
            isUnlocked
              ? "bg-brand-green/10 text-brand-green"
              : "bg-gray-100 dark:bg-slate-700 text-gray-400 dark:text-gray-500"
          }`}
        >
          {isUnlocked ? (
            <Download className="w-6 h-6" />
          ) : (
            <Icon className="w-6 h-6" />
          )}
        </div>

        {/* Content */}
        <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2 group-hover:text-brand-green transition-colors">
          {title}
        </h3>

        {description && (
          <p className="text-sm text-gray-600 dark:text-gray-400 mb-4 line-clamp-2">
            {description}
          </p>
        )}

        {/* Action */}
        <div
          className={`flex items-center gap-2 text-sm font-medium ${
            isUnlocked ? "text-brand-green" : "text-gray-500 dark:text-gray-400"
          }`}
        >
          {isUnlocked ? (
            <>
              <Download className="w-4 h-4" />
              {t.download}
            </>
          ) : (
            <>
              <Lock className="w-4 h-4" />
              {t.unlockToAccess}
            </>
          )}
        </div>

        {/* Hover overlay for locked state */}
        {!isUnlocked && (
          <div className="absolute inset-0 bg-brand-green/0 group-hover:bg-brand-green/5 rounded-xl transition-colors" />
        )}
      </div>

      <RecaptchaWrapper>
        <LeadGateModal
          isOpen={showModal}
          onClose={handleCloseModal}
          onSuccess={handleSuccess}
          lang={lang}
          resourceTitle={title}
          resourceType={
            resourceType === "video" || resourceType === "webinar"
              ? "guide"
              : resourceType
          }
        />
      </RecaptchaWrapper>
    </>
  );
}
