"use client";

import Image from "next/image";
import { FcWorkflow } from "react-icons/fc";
import { usePathname, useRouter } from "next/navigation";

import { Post } from "@/types/blog/blogTypes";
import { ClientResourcesBlogTags } from "@/constants/blog-data";
import NotFound from "@/app/[...not-found]/page";
import Button from "@/components/common/button";
import HeroSection from "@/components/pages/client/resources/hero-section";
import { INTERNAL_PAGES } from "@/constants/pages-mapping/internal-pages-mapping";
import { truncateText } from "@/utils/text-utils";

type ResourceSectionProps = {
  posts: Post[];
};

type ResourcesListProps = {
  post: Post;
  onClick: (slug: string) => void;
};

function ResourcesList({ post, onClick }: ResourcesListProps) {
  return (
    <section className="max-w-3xl m-auto p-8">
      <div className="-mb-6 mt-6 flow-root divide-y divide-gray-200 border-t border-gray-200">
        <div className="py-6 lg:flex">
          <div className="flex flex-col items-center lg:items-start lg:flex-row space-x-4 lg:min-w-0 lg:flex-1 lg:space-x-6">
            <Image
              alt={post.feature_image_alt || ""}
              className="size-36 flex-none rounded object-cover object-center lg:size-56"
              height={144}
              src={post.feature_image || ""}
              width={144}
            />
            <div className="min-w-0 flex-1 pt-1.5 lg:pt-0 space-y-2">
              <h3 className="font-inter font-bold truncate">{post.title}</h3>
              <p className="font-noto text-gray-800 dark:text-gray-300 text-sm">
                {(() => {
                  const textToUse = post.custom_excerpt || post.excerpt;

                  // Filter out PDF related content
                  const filteredText = textToUse
                    .split("\n")
                    .filter((line) => !line.includes(".pdf"))
                    .join(" ");

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

                  return truncateText(cleanDescription, 300);
                })()}
              </p>
            </div>
          </div>
          <div className="mt-6 space-y-4 lg:ml-6 lg:mt-0 lg:w-40 lg:flex-none">
            <Button
              btnLabel="View resource"
              customVariant="client"
              onClick={() => onClick(post.slug)}
            />
          </div>
        </div>
      </div>
    </section>
  );
}

function ResourceSection({ posts }: ResourceSectionProps) {
  const router = useRouter();
  const hasPosts = posts.length > 0;
  const pathname = usePathname();
  const lastPathSegment = pathname.split("/").pop() || "";

  const sectionMapper: Record<string, string> = {
    guides: "Guides",
    "templates-checklists": "Templates and checklists",
    "industry-reports": "Industry reports",
  };

  const sectionName = sectionMapper[lastPathSegment] || "";

  const pathnameIsValid = () => {
    return Object.values(ClientResourcesBlogTags).some((tag) =>
      tag.endsWith(lastPathSegment),
    );
  };

  const handleViewResource = (slug: string) => {
    router.push(`${pathname}/${slug}`);
  };

  const handleViewAllResources = () => {
    router.push(INTERNAL_PAGES.client.resources);
  };

  if (!pathnameIsValid()) return <NotFound />;

  return (
    <div className="py-8 mt-4 font-noto text-center lg:text-start">
      <HeroSection isSection section={sectionName} />
      {!hasPosts && (
        <div className="flex flex-col items-center space-y-8 my-32 px-12">
          <FcWorkflow className="text-4xl mb-4" size={72} />
          <p>
            We&apos;re working hard to curate the essential guides and insights
            on user recruitment and research. Check back soon for expert
            resources at your fingertips!
          </p>
          <Button
            btnLabel="View all resources"
            customVariant="client"
            onClick={handleViewAllResources}
          />
        </div>
      )}
      {hasPosts && (
        <ul>
          {posts.map((post) => (
            <ResourcesList
              key={post.id}
              post={post}
              onClick={() => handleViewResource(post.slug)}
            />
          ))}
        </ul>
      )}
    </div>
  );
}

export default ResourceSection;
