import { useEffect, useState } from "react";
import { ImagePath } from "@/utils/imagePath";
import { Texts } from "@/utils/texts";
import Image from "next/image";

interface GhostAuthor {
  name: string;
  profile_image: string | null;
  bio: string | null;
}

interface GhostPost {
  id: string;
  title: string;
  feature_image: string | null;
  custom_excerpt?: string;
  excerpt: string;
  authors: GhostAuthor[];
}

const samplePosts: GhostPost[] = [
  {
    id: "1",
    title: "The Future of AI in Everyday Life",
    feature_image: ImagePath.toolkit1,
    excerpt: "Explore how artificial intelligence is transforming our daily lives and what the future holds for AI integration in everyday tasks.",
    authors: [
      {
        name: "John Smith",
        profile_image: ImagePath.circle_arrow,
        bio: "AI enthusiast and tech writer"
      }
    ]
  },
  {
    id: "2",
    title: "Building Better Habits with Technology",
    feature_image: ImagePath.toolkit2,
    excerpt: "Discover how modern technology can help you build and maintain better habits for a more productive life.",
    authors: [
      {
        name: "Sarah Johnson",
        profile_image: ImagePath.circle_arrow,
        bio: "Productivity expert and coach"
      }
    ]
  },
  {
    id: "3",
    title: "The Power of Positive Thinking",
    feature_image: ImagePath.learn,
    excerpt: "Learn how positive thinking can transform your life and practical ways to cultivate a positive mindset every day.",
    authors: [
      {
        name: "Michael Chen",
        profile_image: ImagePath.circle_arrow,
        bio: "Mental health advocate and writer"
      }
    ]
  },
  {
    id: "4",
    title: "Sustainable Living in the Modern World",
    feature_image: ImagePath.crystal,
    excerpt: "Tips and strategies for living a more sustainable lifestyle in today's fast-paced world.",
    authors: [
      {
        name: "Emily Davis",
        profile_image: ImagePath.circle_arrow,
        bio: "Environmental activist and writer"
      }
    ]
  },
  {
    id: "5",
    title: "The Art of Mindfulness",
    feature_image: ImagePath.toolkit1,
    excerpt: "A beginner's guide to mindfulness meditation and its benefits for mental well-being.",
    authors: [
      {
        name: "Robert Wilson",
        profile_image: ImagePath.circle_arrow,
        bio: "Mindfulness teacher and meditation guide"
      }
    ]
  }
];

const Inspired = () => {
  const [posts, setPosts] = useState<GhostPost[]>(samplePosts);
  const [loading, setLoading] = useState<boolean>(false);
  const [visiblePostsCount, setVisiblePostsCount] = useState<number>(3); // Controls how many posts are shown

  const handleSeeMore = () => {
    setVisiblePostsCount((prevCount) => prevCount + 3);
  };

  // async function fetchPosts(): Promise<GhostPost[]> {
  //   const response = await fetch(
  //     `${process.env.NEXT_PUBLIC_GHOST_API_URL}/ghost/api/v3/content/posts/?key=${process.env.NEXT_PUBLIC_GHOST_CONTENT_API_KEY}&filter=featured:true&include=tags,authors`
  //   );
  //   const data = await response.json();
  //   return data.posts || [];
  // }

  // useEffect(() => {
  //   fetchPosts()
  //     .then((posts) => {
  //       setPosts(posts);
  //       setLoading(false);
  //     })
  //     .catch((error) => {
  //       console.error("Error fetching posts:", error);
  //       setLoading(false);
  //     });
  // }, []);

  return (
    <div className="my-20">
      <div className="text-center">
        <h1 className="my-20 text-3xl md:text-7xl font-semibold tracking-tight text-gray-900 dark:text-white">
          {Texts.inspired}
        </h1>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-10 max-w-screen-xl">
        {posts.length > 0 ? (
          posts.slice(0, visiblePostsCount).map((post) => (
            <div
              key={post.id}
              className="group transition duration-300 ease-in-out hover:bg-white bg-black text-white hover:text-black p-8 max-w-sm rounded-2xl dark:bg-gray-800 dark:border-gray-700 flex flex-col justify-between min-h-[500px] cursor-pointer"
              style={{
                cursor: `url(${ImagePath.circle_arrow_dark}), pointer`
              }}
            >
              {post.feature_image && (
                <Image
                  className="rounded-lg object-cover"
                  src={post.feature_image}
                  alt={post.title || "Featured Post"}
                  width={500}
                  height={250}
                  loading="lazy"
                  style={{ height: "250px" }}
                />
              )}
              <h5 className="my-8 text-xl font-semibold tracking-tight group-hover:text-black dark:text-gray-900">
                {post.title}
              </h5>
              <p className="mb-3 text-lg font-normal text-gray-400 group-hover:text-gray-700 dark:text-gray-400 flex-grow">
                {post.custom_excerpt || `${post.excerpt.slice(0, 100)}...`}
              </p>
              <hr className="h-px my-8 bg-gray-800 border-0 dark:bg-gray-700 group-hover:bg-gray-300" />
              <figcaption className="flex items-center justify-center">
                {post.authors.length > 0 && post.authors[0].profile_image ? (
                  <>
                    <Image
                      className="rounded-2xl"
                      src={post.authors[0].profile_image}
                      alt={post.authors[0].name}
                      width={36}
                      height={36}
                      loading="lazy"
                    />
                    <div className="ml-6 font-medium text-left">
                      <div className="text-xl font-bold group-hover:text-black dark:text-white">
                        {post.authors[0].name}
                      </div>
                      <div className="text-base text-gray-500 group-hover:text-gray-700 dark:text-gray-400">
                        {post.authors[0].bio || "Ghost Author"}
                      </div>
                    </div>
                  </>
                ) : (
                  <p className="text-center text-gray-400 group-hover:text-gray-700">
                    Unknown author
                  </p>
                )}
              </figcaption>
            </div>
          ))
        ) : (
          <p className="text-center text-gray-500">No featured posts found.</p>
        )}
      </div>


      {posts.length > 3 && visiblePostsCount < posts.length && (
        <div className="text-center">
          <button
            type="button"
            onClick={handleSeeMore}
            className="my-20 bg-white text-black max-w-fit h-16 text-grey-900 focus:ring-4 focus:outline-none font-medium rounded-full text-xl px-5 py-2.5 text-center inline-flex items-center justify-center hover:bg-gray-100"
          >
            {Texts.see_more}
            <Image
              src={ImagePath.circle_arrow_dark}
              alt="See more"
              className="h-9 ml-6 arrow text-black animate-pulse"
              width={36}
              height={36}
              loading="lazy"
            />
          </button>
        </div>
      )}
    </div>
  );
};

export default Inspired;


