"use client";
import { useParams } from "next/navigation";
import { format } from "date-fns";
import { useEffect, useState } from "react";
import { ArticleDetails } from "@/types/article";

const ArticleDetail = () => {
  const { slug } = useParams();
  const [article, setArticle] = useState<ArticleDetails | null>(null);

  useEffect(() => {
    if (slug) {
      const fetchArticleDetail = async () => {
        const response = await fetch(
          `http://localhost:5000/articleDetails?path=${slug}`
        );
        const data = await response.json();
        setArticle(data[0]);
      };
      fetchArticleDetail();
    }
  }, [slug]);

  if (!article) {
    return (
      <div className="text-center text-2xl py-[50px] font-bold italic">
        Article not found.
      </div>
    );
  }

  return (
    <div className="page-article">
      <div className="container">
        <div className="content-article-detail">
          <div className="time">
            {format(new Date(article.last_update * 1000), "dd/MM/yyyy")}
          </div>
          <h1 className="title-article">{article.title}</h1>

          <div className="summary">{article.summary}</div>

          <div className="thumbnail">
            <img
              src={`https://hurasoft8.hurasoft.com/${article.image.large}`}
              width="100%"
              height="100%"
              alt=""
            />
          </div>

          <div
            className="content nd"
            dangerouslySetInnerHTML={{ __html: article.content }}
          />
        </div>
      </div>
    </div>
  );
};

export default ArticleDetail;
