import Typography from "@/shared/ui/components/Typography/Typography";
import "./NewsDetails.scss";
import { apiInstance } from "@/shared/config/apiConfig";
import { INews } from "@/shared/types/news-type";
import Image from "next/image";
import message from "./icons/message.svg";
import calendar from "./icons/calendar.svg";
import ReviewSection from "@/widgets/ReviewSection/ReviewSection";
import BreadCrumbs from "@/features/BreadCrumbs/BreadCrumbs";
import { Metadata } from "next";
import parse from "html-react-parser";

export async function generateMetadata({
  params,
}: {
  params: { id: string };
}): Promise<Metadata> {
  const response = await apiInstance.get<INews>(`/news/${params.id}/`);

  return {
    title: response.data.title,
    description: response.data.description,
    openGraph: {
      images: [response.data.image],
      type: "article",
      publishedTime: response.data.created_at,
    },
  };
}
function convertLinksToHtml(text: string) {
  const urlPattern =
    /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[-A-Z0-9+&@#\/%=~_|$])[\s.,;]?/gi;
  return text.replace(urlPattern, (url) => {
    const href = url.trim();
    return `<a href="${href}" target="_blank" rel="noopener noreferrer">${href}</a>`;
  });
}
const formatDescription = (text: string) => {
  return text.replace(/(\r\n|\n|\r)/g, "<br />");
};

const NewsDetails = async ({
  params,
}: {
  params: { id: string; новость: string };
}) => {
  const getNewsById = async () => {
    const response = await apiInstance.get<INews>(`/news/${params.id}/`);

    return response.data;
  };

  const data = await getNewsById();

  const months: Record<string, string> = {
    "01": "Январь",
    "02": "Февраль",
    "03": "Март",
    "04": "Апрель",
    "05": "Май",
    "06": "Июнь",
    "07": "Июль",
    "08": "Август",
    "09": "Сентябрь",
    "10": "Октябрь",
    "11": "Ноябрь",
    "12": "Декабрь",
  };
  const htmlContentWithLinks = convertLinksToHtml(data.description);
  const formattedHtmlContent = formatDescription(htmlContentWithLinks);
  return (
    <div className="news-details page-padding">
      <BreadCrumbs />
      <Typography element="h2">{data.title}</Typography>

      <div className="news-details__img">
        <img id="news-img" src={data.image} alt="News Image" />
        <div className="news-details__date-and-reviews">
          <div className="news-details__date">
            <Image src={calendar} alt="Calendar Icon" />
            <p>
              {months[data.created_at.slice(5, 7)]}{" "}
              {data.created_at.slice(8, 10) === "0"
                ? data.created_at.slice(9, 10)
                : data.created_at.slice(8, 10)}
              , {data.created_at.slice(0, 4)}
            </p>
          </div>

          <div className="news-details__reviews">
            <Image src={message} alt="Message Icon" />
            <p>Комментарии: {data.count_reviews}</p>
          </div>
        </div>
      </div>

      <div className="news-details__text">
        <h3>{data.title}</h3>
        <div className="news-details__description">
          {parse(formattedHtmlContent)}
        </div>
      </div>

      <ReviewSection endpoint="news" id={data.id} />
    </div>
  );
};

export default NewsDetails;
