"use client";

import fetchData from "@/api/fetch-data";
import AlertWarning from "@/app/ui/shared/AlertWarning";
import CustomBreadcrumb from "@/app/ui/shared/CustomBreadcrumb";
import FallbackImage from "@/app/ui/shared/FallbackImage";
import Loading from "@/app/ui/shared/Loading";
import { toastSuccess } from "@/services/custom-toast";
import { useQuery } from "@tanstack/react-query";
import { useLocale, useTranslations } from "next-intl";
import Link from "next/link";
// import DOMPurify from "dompurify";
import {
  FaFacebook,
  FaLink,
  FaLinkedin,
  FaPinterestP,
  FaTwitter,
  FaWhatsapp,
} from "react-icons/fa6";

export default function SingleArticle({ params }) {
  const { id } = params;
  const t = useTranslations("single-article");
  const locale = useLocale();

  const socials = [
    {
      id: 1,
      color: "#77878F",
      icon: FaLink,
      action: (url) => {
        navigator.clipboard.writeText(url);
        toastSuccess(t("copysuccess"));
      },
    },
    {
      id: 2,
      color: "#CB2027",
      icon: FaPinterestP,
      linkGenerator: (url, title) =>
        `https://pinterest.com/pin/create/button/?url=${encodeURIComponent(
          url
        )}&description=${encodeURIComponent(title)}`,
    },
    {
      id: 3,
      color: "#0077B5",
      icon: FaLinkedin,
      linkGenerator: (url, title) =>
        `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(
          url
        )}&title=${encodeURIComponent(title)}`,
    },
    {
      id: 4,
      color: "#1DA1F2",
      icon: FaTwitter,
      linkGenerator: (url, title) =>
        `https://twitter.com/intent/tweet?url=${encodeURIComponent(
          url
        )}&text=${encodeURIComponent(title)}`,
    },
    {
      id: 5,
      color: "#3B5998",
      icon: FaFacebook,
      linkGenerator: (url) =>
        `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(
          url
        )}`,
    },
    {
      id: 6,
      color: "#25D366",
      icon: FaWhatsapp,
      linkGenerator: (url, title) =>
        `https://wa.me/?text=${encodeURIComponent(title + " " + url)}`,
    },
  ];

  const dateFormat = (dateStr) => {
    if (!dateStr) return "";
    const formattedDate = dateStr.split(" ")[0];
    const date = new Date(formattedDate);

    if (isNaN(date.getTime())) {
      return t("invalid-date");
    }

    if (locale === "ar") {
      const dayName = new Intl.DateTimeFormat("ar-EG", {
        weekday: "long",
      }).format(date);
      const datePart = new Intl.DateTimeFormat("ar-EG", {
        day: "numeric",
        month: "long",
      }).format(date);
      return `${datePart} ${dayName}`;
    } else {
      return new Intl.DateTimeFormat("en-US", {
        weekday: "long",
        day: "numeric",
        month: "long",
      }).format(date);
    }
  };

  const { data, isLoading, error } = useQuery({
    queryKey: ["article_details", id, locale],
    queryFn: async () => {
      return fetchData({ endPoint: `/articles/${id}`, locale });
    },
    staleTime: 1000 * 60 * 5,
  });

  if (data?.status === "error") {
    return <AlertWarning text={data.message} />;
  }

  if (isLoading) {
    return <Loading />;
  }

  if (error || data?.error) {
    const errorMessage =
      error?.message || data?.message || t("unexpected-error");
    const suggestion = t("try-again");
    return <AlertWarning text={`${errorMessage} - ${suggestion}`} />;
  }

  const articleUrl = typeof window !== "undefined" ? window.location.href : "";

  const blockquotes = data?.data?.content
    ?.match(/<blockquote>(.*?)<\/blockquote>/g)
    ?.map((quote) => quote.replace(/<\/?blockquote>/g, "").trim());

  return (
    <>
      <CustomBreadcrumb subs={true} />
      <section className="container mt-4 mb-10 lg:mb-20 lg:mt-8 text-justify">
        <FallbackImage
          src={data?.data?.image || "/default-image.jpg"}
          width={1000}
          height={500}
          className="w-full object-cover max-h-96"
          alt={data?.data?.title || "Article Image"}
        />

        <div className="grid md:grid-cols-2 items-start mt-10 mb-12">
          <div className="space-y-2 max-md:text-center max-md:mb-4">
            <h1 className="font-bold text-main text-xl mb-4 lg:mb-8  md:text-3xl lg:text-4xl">
              {data?.data?.title}
            </h1>
            <div className="flex gap-4 max-lg:flex-col">
              <div className="font-light text-lg">
                <span className="">{t("author-by")}: </span>
                <span className="text-dark font-semibold"> {data?.data?.owner}</span>
              </div>
              <p className="font-normal text-gray-500 text-lg">
                {dateFormat(data?.data?.last_edit_date)}
              </p>
            </div>
          </div>
          <div className="flex justify-end max-md:m-auto gap-3 items-center">
            {socials.map((item) => {
              const isCopyAction = !!item.action;
              const href = isCopyAction
                ? undefined
                : item.linkGenerator(articleUrl, data?.data?.title);

              return isCopyAction ? (
                <button
                  key={item.id}
                  onClick={() => item.action(articleUrl)}
                  className="p-3 2xl:p-5 rounded-full hover:scale-110 duration-500"
                  style={{ backgroundColor: item.color }}
                >
                  <item.icon size={15} className="text-white" />
                </button>
              ) : (
                <Link
                  key={item.id}
                  href={href}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="p-3 2xl:p-5 rounded-full hover:scale-110 duration-500"
                  style={{ backgroundColor: item.color }}
                  aria-label={`Share on ${item.icon.name}`}
                >
                  <item.icon size={15} className="text-white" />
                </Link>
              );
            })}
          </div>
        </div>

        <div
          className=" lg:text-lg"
          style={{
            lineHeight: "2.5rem",
          }}
          dangerouslySetInnerHTML={{
            __html: data?.data?.content || "",
          }}
        ></div>

        {blockquotes && blockquotes.length > 0 && (
          <div className="my-8">
            {blockquotes.map((quote, index) => (
              <blockquote
                key={index}
                className="p-4 italic border-l-4 border-dark"
              >
                {quote}
              </blockquote>
            ))}
          </div>
        )}
      </section>
    </>
  );
}
