import { useEffect, useState } from "react";
import GhostContentAPI from "@tryghost/content-api";
import { ImagePath } from "@/utils/imagePath";
import { PostOrPage } from '@tryghost/content-api';

// Initialize Ghost Content API
const api = new GhostContentAPI({
  url: process.env.NEXT_PUBLIC_GHOST_API_URL!,
  key: process.env.NEXT_PUBLIC_GHOST_CONTENT_API_KEY!,
  version: "v3"
});

export default function Positions() {
  const [posts, setPosts] = useState<PostOrPage[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);
  const [selectedPost, setSelectedPost] = useState<any>(null); // State for selected post
  const [isModalOpen, setIsModalOpen] = useState(false); // State for modal visibility

  useEffect(() => {
    const fetchPosts = async () => {
      try {
        const data = await api.posts.browse({
          limit: "all",
          filter: "tag:jobs"
        });
        setPosts(data);
      } catch (err) {
        console.error("Error fetching posts:", err);
        setError(true);
      } finally {
        setLoading(false);
      }
    };

    fetchPosts();
  }, []);

  const openModal = (post: any) => {
    setSelectedPost(post);
    setIsModalOpen(true);
  };

  const closeModal = () => {
    setIsModalOpen(false);
    setSelectedPost(null);
  };

  if (loading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error loading posts.</div>;
  }

  return (
    <div className="m-0">
      <div className="w-full max-w-screen-xl my-20 md:my-40">
        <div className="text-start">
          <h1 className="mb-10 md:mb-20 text-3xl md:text-7xl font-medium tracking-tight text-gray-900 dark:text-white">
            Open Positions
          </h1>
        </div>
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-10">
          {posts.map((post: any) => (
            <div
              key={post.id}
              className="text-black p-8 w-full bg-white rounded-2xl border border-gray-200 dark:bg-gray-800 dark:border-gray-700 cursor-pointer"
              onClick={() => openModal(post)}
            >
              <h5 className="text-2xl md:text-3xl font-normal tracking-tight dark:text-gray-900">
                {post.title}
              </h5>
              <div className="flex mt-4 md:mt-6">
                <img
                  src={ImagePath.remote}
                  className="h-7 mr-2"
                  alt="Remote"
                />
                <p className="text-lg md:text-xl font-normal text-gray-800">
                  {post.custom_excerpt || "Remote"}
                </p>
                <img
                  src={ImagePath.time}
                  className="h-7 mr-2 ml-10"
                  alt="Full-time"
                />
                <p className="text-lg md:text-xl font-normal text-gray-800">
                  Full-time
                </p>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Modal */}
      {isModalOpen && selectedPost && (
        <div className="fixed inset-0 flex items-center justify-center z-50 bg-gray-900 bg-opacity-50">
          <div className="bg-white rounded-2xl p-8 max-w-lg w-full relative">
            <button
              onClick={closeModal}
              className="absolute top-4 right-4 text-2xl font-bold text-gray-700"
            >
              &times;
            </button>
            <h2 className="text-2xl font-bold mb-4 text-black">{selectedPost.title}</h2>
            <div
              className="post-body text-gray-700"
              dangerouslySetInnerHTML={{ __html: selectedPost.html }}
            ></div>
          </div>
        </div>
      )}

      <style jsx>{`
        .post-body {
          max-height: 400px;
          overflow-y: auto;
        }
      `}</style>
    </div>
  );
}
