"use client";
import { useState, SetStateAction, useEffect } from "react";
import Image from "next/legacy/image";
import Link from "next/link";
import { AnimatePresence, motion } from "framer-motion";
import { getValidImageUrl, getValidImageAlt, FALLBACK_IMAGES } from "@/lib/imageUtils";
import PostFilterButtons from "./PostFilterButtons";
import { useBlogPosts } from "@/lib/hooks/useBlog";

interface PostFilterItemsProps {
  currentPage: number;
  onPageChange: (page: number) => void;
  onTotalPagesChange: (totalPages: number) => void;
  postsPerPage?: number;
}

const PostFilterItems = ({ currentPage, onPageChange, onTotalPagesChange, postsPerPage = 10 }: PostFilterItemsProps) => {
  const [active, setActive] = useState("all");
  const { posts: allPosts, loading, error, totalCount } = useBlogPosts({
    category: active === "all" ? undefined : active,
    page: currentPage,
    page_size: postsPerPage
  });
  const [displayData, setDisplayData] = useState<any[]>([]);

  useEffect(() => {
    if (!loading && allPosts.length > 0) {
      setDisplayData(allPosts);
    }
  }, [allPosts, loading]);

  // Calculate and update total pages when totalCount changes
  useEffect(() => {
    if (totalCount !== undefined && totalCount !== null) {
      const calculatedTotalPages = Math.ceil(totalCount / postsPerPage);
      onTotalPagesChange(calculatedTotalPages);
    }
  }, [totalCount, postsPerPage, onTotalPagesChange]);

  const handleCategoryClick = (category: SetStateAction<string>) => {
    if (category === active) return;
    setActive(category);
    setDisplayData([]);
    onPageChange(1); // Reset to page 1 when category changes

    // The API call will be triggered by the change in active state
    // which will update allPosts and trigger the useEffect above
  };

  if (loading && displayData.length === 0) {
    return (
      <>
        <PostFilterButtons active={active} handleClick={handleCategoryClick} />
        <div className="row mt-60">
          <div className="col-12">
            <p className="text-center">Loading posts...</p>
          </div>
        </div>
      </>
    );
  }

  if (error) {
    return (
      <>
        <PostFilterButtons active={active} handleClick={handleCategoryClick} />
        <div className="row mt-60">
          <div className="col-12">
            <p className="text-center text-danger">Error loading posts. Please try again later.</p>
          </div>
        </div>
      </>
    );
  }

  return (
    <>
      <PostFilterButtons active={active} handleClick={handleCategoryClick} />
      <motion.div className="row mt-60 masonry-grid" layout>
        <AnimatePresence>
          {displayData.map((item) => {
            return (
              <motion.div
                className="col-12 col-lg-6 grid-item-main"
                key={item.id}
                layout
                initial={{ opacity: 0, scale: 0.6 }}
                animate={{ opacity: 1, scale: 1 }}
                exit={{ opacity: 0, scale: 0.6 }}
                transition={{ duration: 0.6 }}
              >
                <div className="tp-lp-slider__single topy-tilt">
                  <div className="thumb mb-24">
                    <Link
                      href={`/insights/${item.slug}`}
                      className="w-100 overflow-hidden d-block"
                     >
                      <div className="parallax-image-wrap">
                        <div className="parallax-image-inner">
                          <Image
                            src={getValidImageUrl(item.thumbnail, FALLBACK_IMAGES.BLOG)}
                            className="w-100 mh-220 parallax-image"
                            alt={getValidImageAlt(item.title)}
                            width={400}
                            height={220}
                          />
                        </div>
                      </div>
                    </Link>
                  </div>
                  <div className="content">
                    <div className="tp-lp-post__meta mb-24 mt-8">
                      <p className="author text-xs text-tertiary">
                        {item.author_name || 'Admin'}
                      </p>
                      <span></span>
                      <p className="date text-xs text-tertiary">
                        {new Date(item.published_at || item.created_at).toLocaleDateString('en-US', {
                          day: 'numeric',
                          month: 'short',
                          year: 'numeric'
                        })}
                      </p>
                    </div>
                    <h5 className="mt-8 fw-5 text-secondary">
                      <Link href={`/insights/${item.slug}`}>{item.title}</Link>
                    </h5>
                  </div>
                </div>
              </motion.div>
            );
          })}
        </AnimatePresence>
      </motion.div>
    </>
  );
};

export default PostFilterItems;
