"use client";

import Image from "next/image";
import {
  Card,
  CardBody,
  CardFooter,
  CardHeader,
  Chip,
} from "@nextui-org/react";
import { useEffect, useState } from "react";
import LoadingBar from "react-top-loading-bar";
import { useRouter } from "next/navigation";
import { FaChevronDown, FaCircleInfo, FaHouseLaptop } from "react-icons/fa6";
import { FaBook, FaFileContract, FaHandHolding } from "react-icons/fa";

import { Post } from "@/types/blog/blogTypes";
import Breadcrumbs from "@/components/common/breadcrumbs";
import { INTERNAL_PAGES } from "@/constants/pages-mapping/internal-pages-mapping";
import { formatSection } from "@/utils/posts-utils";
import { truncateText } from "@/utils/text-utils";
import { InternalParticipantBlogTags } from "@/constants/blog-data";
import PFRSamLogo from "@/components/common/sprites/pfr-sam-logo-sprite";

type ListOfPostsProps = {
  posts: Post[];
  catchySentence: string;
  section: string;
};

function ListOfPosts({ posts, catchySentence, section }: ListOfPostsProps) {
  const router = useRouter();
  const [progress, setProgress] = useState(0);
  const [itemsPerPage, setItemsPerPage] = useState(9);
  const hasPosts = posts && posts.length > 0;
  const [showChevron, setShowChevron] = useState(true);

  const increaseItems = () => {
    setItemsPerPage(
      (prevItemsToShow) =>
        prevItemsToShow + (window.innerWidth <= 1024 ? 9 : 18),
    );
  };

  const handleOnPress = (slug: string) => {
    router.push(
      `${INTERNAL_PAGES.participant.howItWorks.homepage}/${section}/${slug}`,
    );
  };

  useEffect(() => {
    const handleScroll = () => {
      if (window.scrollY > 0) {
        setShowChevron(false);
      }
    };

    window.addEventListener("scroll", handleScroll);

    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

  useEffect(() => {
    const handleScroll = () => {
      const scrollPosition =
        window.scrollY || document.documentElement.scrollTop;
      const windowHeight = window.innerHeight;
      const documentHeight = document.documentElement.offsetHeight;

      // This threshold value is required for mobile and tablets, otherwise the user will have to scroll until the bottom of the page, past footer.
      const threshold = window.innerWidth <= 1024 ? 500 : 1000;

      if (window.innerWidth <= 1024) {
        if (windowHeight + scrollPosition >= documentHeight - threshold) {
          setProgress(50);
          increaseItems();
          setProgress(100);
        }
      } else {
        if (windowHeight + scrollPosition >= documentHeight) {
          setProgress(50);
          increaseItems();
          setProgress(100);
        }
      }
    };

    window.addEventListener("scroll", handleScroll);
    window.addEventListener("touchmove", handleScroll);
    return () => {
      window.removeEventListener("scroll", handleScroll);
      window.removeEventListener("touchmove", handleScroll);
    };
  }, []);

  const getIconForSection = (section: InternalParticipantBlogTags) => {
    switch (section) {
      case InternalParticipantBlogTags.ABOUT_US:
        return <PFRSamLogo width={16} />;
      case InternalParticipantBlogTags.ABOUT_RESEARCH:
        return <FaCircleInfo />;
      case InternalParticipantBlogTags.RESEARCH_STORIES:
        return <FaBook />;
      case InternalParticipantBlogTags.REGISTRATION_HUB:
        return <FaHouseLaptop />;
      case InternalParticipantBlogTags.HELPFUL_GUIDES:
        return <FaHandHolding />;
      case InternalParticipantBlogTags.POLICIES:
        return <FaFileContract />;
      default:
        return null;
    }
  };

  return (
    <div className="py-4">
      {showChevron && (
        <div className="fixed inset-x-0 bottom-0 flex justify-center z-50">
          <FaChevronDown className="text-4xl text-atomic-tangerine dark:text-persian-green animate-bounce" />
        </div>
      )}
      <div className="w-full flex flex-col justify-center items-center text-center max-w-3xl mx-auto py-8 space-y-4">
        <Breadcrumbs />
        <span className="text-center font-noto text-sm font-medium tracking-widest uppercase">
          {formatSection(section)}
        </span>
        <h1 className="text-3xl md:text-5xl xl:text-6xl font-black font-inter text-center w-full text-black dark:text-white">
          {catchySentence}
        </h1>
      </div>
      {!hasPosts && (
        <p className="text-start font-medium text-lg font-inter ps-12 my-12">
          No posts found for this category.
        </p>
      )}
      {hasPosts && (
        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 xxxl:grid-cols-6 gap-4 mx-8 md:mx-12 xl:mx-48 my-12">
          {posts.slice(0, itemsPerPage).map((post, index) => {
            return (
              <Card
                key={`post-card-${index}`}
                disableAnimation
                isPressable
                className="bg-white dark:bg-[#18181a] rounded shadow-none light hover:bg-gray-100 hover:dark:bg-[#39393e]"
                onPress={() => handleOnPress(post.slug)}
              >
                <CardHeader className="p-0">
                  <Image
                    alt={post.feature_image_alt || ""}
                    className="object-cover rounded-none h-[250px] w-full"
                    height={1000}
                    loading="eager"
                    src={post.feature_image || ""}
                    width={1000}
                  />
                </CardHeader>
                <CardBody className="space-y-4 pt-5">
                  <Chip
                    classNames={{
                      content:
                        "font-semibold py-1 flex flex-row items-center gap-1",
                      base: "bg-slate-200 dark:bg-slate-700 text-black dark:text-white font-inter font-extrabold text-xs",
                    }}
                  >
                    {getIconForSection(section as InternalParticipantBlogTags)}
                    {formatSection(section)}
                  </Chip>
                  <span className="font-inter font-bold text-sm text-black dark:text-white text-md h-8 leading-5">
                    {post.title.length > 65
                      ? truncateText(post.title, 65)
                      : post.title}
                  </span>
                  <p className="font-noto text-gray-700 dark:text-gray-300 text-sm">
                    {(() => {
                      const textToUse = post.custom_excerpt || post.excerpt;

                      const cleanDescription = textToUse.replace(
                        /<[^>]*>/g,
                        " ",
                      );

                      return cleanDescription.length > 150
                        ? truncateText(cleanDescription, 150)
                        : cleanDescription;
                    })()}
                  </p>
                </CardBody>
                <CardFooter className="font-inter font-semibold text-xs text-gray-700 dark:text-white/70 justify-between">
                  <span>{post.reading_time + " min read"}</span>
                </CardFooter>
              </Card>
            );
          })}
        </div>
      )}
      <LoadingBar
        className="bg-participant-bittersweet dark:bg-participant-cerulean"
        height={4}
        progress={progress}
        onLoaderFinished={() => setProgress(0)}
      />
    </div>
  );
}

export default ListOfPosts;
