"use client";

import Image from "next/image";
import { Chip, Divider, Button as BaseButton } from "@nextui-org/react";
import DOMPurify from "isomorphic-dompurify";
import parse, { domToReact } from "html-react-parser";
import Link from "next/link";
import {
  FaFacebook,
  FaLinkedin,
  FaWhatsapp,
  FaXTwitter,
} from "react-icons/fa6";
import { FaClock } from "react-icons/fa";

import { Post } from "@/types/blog/blogTypes";
import Breadcrumbs from "@/components/common/breadcrumbs";
import CTAServices from "@/components/pages/client/services/cta-services";
import PFRSamLogo from "@/components/common/sprites/pfr-sam-logo-sprite";
import { SM_LINKS_PARTICIPANT } from "@/constants/pages-mapping/external-pages-mapping";

// this component is also shared with insights blog posts.

type CaseStudySlugProps = {
  post: Post;
};

type PostSocialMediaProps = {
  onClick: (socialId: string) => void;
};

function PostSocialMedia({ onClick }: PostSocialMediaProps) {
  const socialMediaIcons = ["twitter", "facebook", "linkedin", "whatsapp"];

  return (
    <div className="flex flex-row">
      {socialMediaIcons.map((socialId) => (
        <BaseButton
          key={socialId}
          isIconOnly
          aria-label={`Share on ${
            socialId.charAt(0).toUpperCase() + socialId.slice(1)
          }`}
          variant="light"
          onPress={() => onClick(socialId)}
        >
          {(() => {
            const classes = "text-midnightBlue dark:text-paleBlue size-5";

            switch (socialId) {
              case "twitter":
                return <FaXTwitter className={classes} />;
              case "facebook":
                return <FaFacebook className={classes} />;
              case "linkedin":
                return <FaLinkedin className={classes} />;
              case "whatsapp":
                return <FaWhatsapp className={classes} />;
            }
          })()}
        </BaseButton>
      ))}
    </div>
  );
}

function CaseStudySlug(post: CaseStudySlugProps) {
  const { title, html, tags, reading_time } = post.post;

  const tagDisplayNames: { [key: string]: string } = {
    "#client-news": "News",
    "#client-case-studies": "Case studies",
    "#client-how-to": "How to",
    "#client-industry-stories": "Industry stories",
    "#client-community-tips": "Community tips",
  };

  const sanitizedPost = DOMPurify.sanitize(html, {
    ADD_TAGS: ["iframe"],
  });

  const options = {
    replace: (domNode: any) => {
      if (domNode.name === "img") {
        return renderImage(domNode);
      }

      if (domNode.name === "figcaption") {
        return renderFigcaption(domNode, options);
      }

      if (domNode.name === "a") {
        return renderAnchor(domNode, options);
      }

      if (domNode.name === "iframe") {
        return renderIframe(domNode);
      }

      if (domNode.name === "blockquote") {
        return renderBlockquote(domNode, options);
      }

      if (domNode.name === "ol") {
        return renderOrderedList(domNode, options);
      }

      if (domNode.name === "li") {
        return renderListItem(domNode, options);
      }
    },
  };

  const renderImage = (domNode: any) => {
    return (
      <div className="flex items-center justify-center">
        <Image
          alt={domNode.attribs.alt}
          className="object-fill rounded-lg w-full h-full"
          height={1000}
          loading="eager"
          src={domNode.attribs.src}
          width={1000}
        />
      </div>
    );
  };

  const renderFigcaption = (domNode: any, options: any) => {
    const children = domNode.children.map((childNode: any) => {
      if (childNode.name === "a") {
        return renderAnchorChild(childNode);
      }

      if (childNode.type === "text") {
        return childNode.data;
      }

      return domToReact([childNode], options);
    });

    return <figcaption>{children}</figcaption>;
  };

  const renderAnchor = (domNode: any, options: any) => {
    const url = new URL(domNode.attribs.href);
    url.searchParams.delete("ref");

    return (
      <Link
        className="font-medium underline"
        href={url.toString()}
        rel="noopener noreferrer"
        target="_blank"
      >
        {domToReact(domNode.children, options)}
      </Link>
    );
  };

  const renderAnchorChild = (childNode: any) => {
    return childNode.children
      .map((grandChildNode: any) => {
        if (grandChildNode.type === "text") {
          return grandChildNode.data;
        }

        if (grandChildNode.name === "span") {
          return grandChildNode.children[0].data;
        }
      })
      .join("");
  };

  const renderIframe = (domNode: any) => {
    return (
      <iframe
        allowFullScreen={domNode.attribs.allowfullscreen}
        className="my-iframe"
        src={domNode.attribs.src}
        title={domNode.attribs.title || "iframe"}
      />
    );
  };

  const renderOrderedList = (domNode: any, options: any) => {
    return <ol>{domToReact(domNode.children, options)}</ol>;
  };

  const renderListItem = (domNode: any, options: any) => {
    return <li>{domToReact(domNode.children, options)}</li>;
  };

  const renderBlockquote = (domNode: any, options: any) => {
    return (
      <blockquote className="border-s-3 border-midnightBlue dark:border-pfrBasicBlue ps-4 py-2 italic text-black dark:text-white">
        {domToReact(domNode.children, options)}
      </blockquote>
    );
  };

  const handleOnClickSocial = (socialId: string) => {
    const baseUrl = process.env.NEXT_PUBLIC_PFR_WEBSITE_BASE_URL;
    const currentPath = window.location.pathname;
    const encodedUrl = encodeURIComponent(`${baseUrl}${currentPath}`);

    let shareUrl = "";

    switch (socialId) {
      case "facebook":
        shareUrl = `https://www.facebook.com/sharer/sharer.php?u=${encodedUrl}`;
        break;
      case "twitter":
        shareUrl = `https://twitter.com/intent/tweet?url=${encodedUrl}`;
        break;
      case "linkedin":
        shareUrl = `https://www.linkedin.com/shareArticle?mini=true&url=${encodedUrl}`;
        break;
      case "whatsapp":
        shareUrl = `https://api.whatsapp.com/send?text=Check%20out%20this%20article%20from%20People%20for%20Research:%20${encodedUrl}`;
        break;
      default:
        shareUrl = "";
        return;
    }

    window.open(shareUrl, "_blank");
  };

  return (
    <div className="min-h-screen bg-others-mistyGray dark:bg-jet font-noto text-lg">
      <div className="text-black dark:text-white space-y-6 p-8 max-w-7xl mx-auto leading-7">
        <div className="ps-2 pt-8 lg:p-12 space-y-4">
          <Breadcrumbs />
          <div className="flex flex-row justify-between items-center">
            <Chip
              classNames={{
                content: "font-semibold",
                base: "bg-midnightBlue text-white font-inter text-xs mt-1.5",
              }}
              size="sm"
            >
              {tagDisplayNames[tags[0].name]}
            </Chip>
            <div className="flex flex-row justify-between items-center">
              <PostSocialMedia
                onClick={(socialId) =>
                  handleOnClickSocial(
                    socialId as keyof typeof SM_LINKS_PARTICIPANT
                  )
                }
              />
            </div>
          </div>
          <h1 className="font-inter font-black text-2xl sm:text-5xl mb-4">
            {title}
          </h1>
          <div className="flex flex-col lg:flex-row items-start lg:items-center space-y-4 space-x-0 lg:space-y-0 lg:space-x-8 py-4">
            <div className="flex flex-row items-center space-x-2">
              <PFRSamLogo height={20} width={20} />
              <p className="font-inter font-semibold text-xs">
                People for Research
              </p>
            </div>
            <div className="flex flex-row items-center space-x-2">
              <FaClock />
              <span className="font-inter font-semibold text-xs">
                {reading_time} min read
              </span>
            </div>
          </div>
          <Divider />
          <article className="font-noto htmlContent space-y-4">
            {parse(sanitizedPost, options)}
          </article>
        </div>
      </div>
      <CTAServices
        description="Begin your journey with our accredited research recruitment services today."
        title="Your research, our expertise."
        typeOfUsage="case-study"
      />
    </div>
  );
}

export default CaseStudySlug;
