import React, { useState, useEffect } from "react";
import { X } from "lucide-react";

const ActivityModal = () => {
  const [isOpen, setIsOpen] = useState(false);
  const [activityContent, setActivityContent] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchActivityContent = async () => {
      try {
        setIsLoading(true);
        const response = await fetch("/api/activity", {
          headers: {
            "x-from-frontend": "true",
          },
        });
        if (!response.ok) {
          throw new Error("Failed to fetch activity content");
        }
        const data = await response.json();
        console.log("data", data);

        if (data.success && data.data) {
          setActivityContent(data.data[0]);
          setIsOpen(true);
        } else {
          console.log(data.message || "No active activity");
          setActivityContent(null);
        }
      } catch (error) {
        console.error("Error fetching activity content:", error);
        setActivityContent(null);
      } finally {
        setIsLoading(false);
      }
    };

    fetchActivityContent();
  }, []);

  if (!isOpen || !activityContent || isLoading) return null;

  console.log("activityContent", activityContent);

  const hasBackgroundImage = !!activityContent?.backgroundImage;
  const hasBackgroundImageLink = !!activityContent?.backgroundImageLink;

  const CardContent = () => (
    <div
      className="bg-cover bg-center rounded-lg px-6 pb-6 pt-16 max-w-sm w-full mx-4 overflow-hidden"
      style={{
        backgroundImage: `url('${activityContent.backgroundImage}')`,
        width: "80vw",
        minHeight: "50vh",
        backgroundPosition: "top center",
      }}
    >
      <div className="relative z-10 text-white">
        <div className="flex flex-col items-center mb-4 relative w-full">
          <div
            className="text-xl font-bold w-full text-center"
            dangerouslySetInnerHTML={{ __html: activityContent.title }}
          />
        </div>
        <div
          className="overflow-y-auto"
          style={{ maxHeight: "calc(50vh - 100px)" }}
          dangerouslySetInnerHTML={{ __html: activityContent.content }}
        />
      </div>
    </div>
  );

  return (
    <>
      {hasBackgroundImage ? (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="relative">
            <button
              onClick={() => setIsOpen(false)}
              className="absolute -top-16 right-3 text-white hover:text-gray-300 z-20 p-2 rounded-full bg-gray-500  hover:bg-opacity-70 transition-all duration-300"
            >
              <X size={24} />
            </button>
            {hasBackgroundImageLink ? (
              <a
                href={activityContent.backgroundImageLink}
                target="_blank"
                rel="noopener noreferrer"
              >
                <CardContent />
              </a>
            ) : (
              <CardContent />
            )}
          </div>
        </div>
      ) : (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 max-w-sm w-full mx-4">
            <div className="flex flex-col items-center mb-4 relative w-full">
              <div
                className="text-xl font-bold text-black w-full"
                dangerouslySetInnerHTML={{ __html: activityContent.title }}
              ></div>
              <button
                onClick={() => setIsOpen(false)}
                className="text-gray-500 hover:text-gray-700 absolute right-0 top-0"
              >
                <X size={24} />
              </button>
            </div>
            <div
              className="text-gray-700"
              dangerouslySetInnerHTML={{ __html: activityContent.content }}
            />
          </div>
        </div>
      )}
    </>
  );
};

export default ActivityModal;
