"use client";
import {
  convertDateFormat,
  formatMonthString,
  formatTextToHtmlTag,
} from "@/utils/global";
import Image from "next/image";
import {
  CalendarIcon,
  ChevronLeftIcon,
  ChevronRightIcon,
  ClockIcon,
  EyeIcon,
  EyeIconMdi,
  FacebookIcon,
  SquareFacebookIcon,
  SquareLinkedInIcon,
  SquareWhatsappIcon,
  SquareXIcon,
  UserIcon,
} from "../icons";
import { Button } from "@nextui-org/button";
import { usePathname } from "next/navigation";
import Link from "next/link";
import { useEffect, useState } from "react";

export default function DetailNews(props: { data: any; listArticle: any }) {
  const { data, listArticle } = props;
  const [prevArticle, setPrevArticle] = useState("");
  const [nextArticle, setNextArticle] = useState("");
  const pathname = usePathname();
  const shareText = "Humas Polri";

  const handleShare = (platform: string) => {
    let shareLink = "";
    const urls = "https://kontenhumas.com/" + pathname;

    switch (platform) {
      case "facebook":
        shareLink = `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(
          urls
        )}`;
        break;
      case "x":
        shareLink = `https://x.com/intent/tweet?url=${encodeURIComponent(
          urls
        )}&text=${encodeURIComponent(shareText)}`;
        break;
      case "linkedin":
        shareLink = `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(
          urls
        )}`;
        break;
      case "whatsapp":
        shareLink = `https://wa.me/?text=${encodeURIComponent(
          shareText + " " + urls
        )}`;
        break;
      default:
        break;
    }

    const popupWidth = 800;
    const popupHeight = 600;
    const left = window.screenX + (window.innerWidth - popupWidth) / 2;
    const top = window.screenY + (window.innerHeight - popupHeight) / 2;

    window.open(
      shareLink,
      "_blank",
      `width=${popupWidth},height=${popupHeight},top=${top},left=${left},resizable=no,scrollbars=no,toolbar=no,menubar=no,status=no`
    );
  };

  useEffect(() => {
    const index = listArticle.findIndex((item: any) => item?.id === data?.id);
    if (index - 1 == -1) {
      setPrevArticle("");
    } else {
      const prevString = `${listArticle[index - 1]?.id}-${
        listArticle[index - 1]?.slug
      }`;
      setPrevArticle(prevString);
    }
    if (index + 1 == listArticle?.length) {
      setNextArticle("");
    } else {
      const nextString = `${listArticle[index + 1]?.id}-${
        listArticle[index + 1]?.slug
      }`;
      setNextArticle(nextString);
    }
  }, [data, listArticle]);

  function removeImgTags(htmlString?: { __html: string }) {
    const parser = new DOMParser();
    const doc = parser.parseFromString(String(htmlString?.__html), "text/html");

    const images = doc.querySelectorAll("img");
    images.forEach((img) => img.remove());

    return { __html: doc.body.innerHTML };
  }
  return (
    <div className="flex flex-col gap-2 py-4">
      <p className="font-semibold text-xl lg:text-3xl">{data?.title}</p>
      <div className="flex flex-row items-center py-1 text-xs lg:text-lg gap-2 lg:gap-4">
        <div className="flex flex-row items-center gap-1">
          <UserIcon size={16} className="lg:hidden" />
          <UserIcon size={22} className="hidden lg:block" />
          <p className="uppercase">{data?.createdByName}</p>
        </div>
        <div className="flex flex-row items-center gap-1">
          <CalendarIcon size={16} className="lg:hidden" />
          <CalendarIcon size={24} className="hidden lg:block" />
          <p>{formatMonthString(data?.updatedAt)}</p>
        </div>
        <div className="flex flex-row items-center">
          <ClockIcon size={16} className="lg:hidden" />
          <ClockIcon size={24} className="hidden lg:block" />
          <p>{`${new Date(data?.updatedAt)
            .getHours()
            .toString()
            .padStart(2, "0")}:${new Date(data?.updatedAt)
            .getMinutes()
            .toString()
            .padStart(2, "0")}`}</p>
        </div>
        <p className="flex items-center gap-1">
          <EyeIconMdi size={16} className="lg:hidden" />
          <EyeIconMdi size={16} className="hidden lg:block" />
          {data?.viewCount === null ? 0 : data?.viewCount}
        </p>
      </div>
      <div className="flex justify-center my-2 lg:my-5">
        <img
          alt="NextUI hero Image"
          src="/detail.png"
          className="object-cover w-[80%]"
        />
      </div>
      <div
        dangerouslySetInnerHTML={removeImgTags(
          formatTextToHtmlTag(data?.htmlDescription)
        )}
        className="text-sm lg:text-xl lg:leading-8"
      />

      <div className="grid grid-cols-2  md:grid-cols-4 gap-5 my-8">
        <Button
          variant="solid"
          radius="none"
          onPress={() => handleShare("facebook")}
          className="w-[80%] bg-[#3b5998] text-white px-4 py-2 flex flex-row"
        >
          <div className="w-1/4 ">
            <SquareFacebookIcon />
          </div>
          <div className="w-3/4 text-xl ">Facebook</div>
        </Button>
        <Button
          variant="solid"
          radius="none"
          onPress={() => handleShare("x")}
          className="w-[80%] bg-black text-white px-4 py-2 flex flex-row"
        >
          <div className="w-1/4 ">
            <SquareXIcon />
          </div>
          <div className="w-3/4 text-xl ">X</div>
        </Button>
        <Button
          variant="solid"
          radius="none"
          onPress={() => handleShare("linkedin")}
          className="w-[80%] bg-[#0E76A8] text-white px-4 py-2 flex flex-row"
        >
          <div className="w-1/4 ">
            <SquareLinkedInIcon />
          </div>
          <div className="w-3/4 text-xl ">LinkedIn</div>
        </Button>
        <Button
          variant="solid"
          radius="none"
          onPress={() => handleShare("whatsapp")}
          className="w-[80%] bg-[#25D366] text-white px-4 py-2 flex flex-row"
        >
          <div className="w-1/4 ">
            <SquareWhatsappIcon />
          </div>
          <div className="w-3/4 text-xl ">Whatsapp</div>
        </Button>
      </div>
      <div className="grid grid-cols-2 text-black">
        {prevArticle === "" ? (
          <p className="flex flex-row items-center gap-3">
            <ChevronLeftIcon /> Sebelumnya
          </p>
        ) : (
          <Link
            href={`/news/detail/${prevArticle}`}
            className="flex flex-row items-center gap-3 font-semibold"
          >
            <ChevronLeftIcon /> Sebelumnya
          </Link>
        )}

        {nextArticle === "" ? (
          <p className="flex flex-row justify-end items-center gap-3">
            Selanjutnya <ChevronRightIcon />
          </p>
        ) : (
          <Link
            href={`/news/detail/${nextArticle}`}
            className="flex flex-row justify-end items-center gap-3 font-semibold"
          >
            Selanjutnya <ChevronRightIcon />
          </Link>
        )}
      </div>
    </div>
  );
}
