"use client";

import Image from "next/image";
import { Card, CardHeader } from "@nextui-org/react";
import DOMPurify from "isomorphic-dompurify";
import toast from "react-hot-toast";

import { Post } from "@/types/blog/blogTypes";
import { downloadArticlePdf } from "@/utils/download-article-pdf";
import { isTrustedGhostPdfUrl } from "@/utils/ghost-pdf";

type ResourcesAreaProps = {
  resources: {
    guides: Post[];
    "templates-checklists": Post[];
    "industry-reports": Post[];
  };
};

type ResourceCardProps = {
  post: Post;
  onPress: (slug: string, section: string) => void;
};

function ResourceCard({ post, onPress }: ResourceCardProps) {
  return (
    <Card
      key={post.id}
      disableAnimation
      isHoverable
      isPressable
      className="light h-48 xl:h-96 hover:bg-white/80 hover:outline-offset-1 hover:outline-2 hover:outline-midnightBlue hover:dark:outline-pfrBasicBlue shadow-none hover:cursor-pointer"
      onPress={() => onPress(post.slug, post.tags[0].name)}
    >
      <Image
        alt={post.feature_image_alt || ""}
        className="z-0 w-full h-full object-cover"
        height={500}
        src={post.feature_image || ""}
        width={500}
      />
      <div className="absolute inset-0 bg-gradient-to-b from-gray-500 to-black opacity-60 z-10"></div>
      <CardHeader className="absolute inset-0 flex items-center justify-center z-20">
        <div className="text-center">
          <p className="font-bold text-xl text-white leading-5">{post.title}</p>
        </div>
      </CardHeader>
    </Card>
  );
}

function ResourcesArea({ resources }: ResourcesAreaProps) {
  const RESOURCE_KEYS: {
    label: string;
    key: keyof typeof resources;
    subtitle: string;
  }[] = [
    {
      label: "Guides",
      key: "guides",
      subtitle: "In-depth guides and tutorials.",
    },
    {
      label: "Templates and checklists",
      key: "templates-checklists",
      subtitle: "Handy templates and checklists.",
    },
    {
      label: "Industry reports",
      key: "industry-reports",
      subtitle: "Comprehensive industry reports.",
    },
  ];

  const sanitizeAndExtractLink = (html: string) => {
    let pdfLink = "";
    let processedHtml = html;
    const linkMatch = html.match(/kg-file-card[\s\S]*?href="([^"]*)"/);

    if (linkMatch) {
      pdfLink = linkMatch[1];
    }

    processedHtml = processedHtml.replace(
      /<div[^>]*kg-file-card[^>]*>[\s\S]*?<\/a>\s*<\/div>/g,
      "",
    );

    const sanitizedHTML = DOMPurify.sanitize(processedHtml, {
      ADD_TAGS: ["iframe"],
    });
    return { sanitizedHTML, pdfLink };
  };

  const sectionHasPosts = (key: keyof typeof resources) => {
    return resources[key].length > 0;
  };

  const handleDownload = async (post: Post) => {
    const { title, html } = post;
    const { pdfLink } = sanitizeAndExtractLink(html);

    if (!pdfLink || !isTrustedGhostPdfUrl(pdfLink)) {
      toast.error(
        "No downloadable file found. Please try again. If the error persists, contact us.",
      );
      return;
    }

    try {
      await downloadArticlePdf(pdfLink, title);

      toast.success(`"${title}" downloaded successfully to your device.`);
    } catch (error) {
      toast.error(
        "Download failed. Please try again. If the error persists, contact us.",
      );
    }
  };

  return (
    <div className="min-h-screen py-12">
      {RESOURCE_KEYS.map(({ label, subtitle, key }, index) => (
        <section key={index} className="lg:ps-20">
          <h2 className="text-3xl font-inter font-black text-center lg:text-start">
            {label}
          </h2>
          <h3 className="text-base font-noto mt-1 text-center lg:text-start">
            {subtitle}
          </h3>
          {!sectionHasPosts(key) && (
            <p className="py-8 mt-4 text-gray-600 dark:text-gray-200 font-noto text-center px-12 lg:px-0 lg:text-start">
              We&apos;re working on curating {label.toLocaleLowerCase()}. Check
              back soon for expert resources at your fingertips.
            </p>
          )}
          {sectionHasPosts(key) && (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 px-12 py-8 lg:px-0 lg:pe-12">
              {resources[key].map((post) => (
                <ResourceCard
                  key={post.id}
                  post={post}
                  onPress={() => handleDownload(post)}
                />
              ))}
            </div>
          )}
        </section>
      ))}
    </div>
  );
}

export default ResourcesArea;
