import React, { useState, useEffect, useCallback } from "react";
import { useLocation, useNavigate, Link } from "react-router-dom";
import { NewsArticle } from "../../services/types";
import { useMutation } from "@tanstack/react-query";
import { useAppDispatch } from "../../hooks/useRedux";
import { startLoading, stopLoading } from "../../features/loading/loadingSlice";
import { articleApi } from "../../apis/articleApi";
import { Article } from "../../services/article/types";
import { useTranslation } from "react-i18next";

const ArticleDetailView: React.FC = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const { t } = useTranslation();

  const article = location.state?.article as Article;
  const [articleDetail, setArticleDetail] = useState<Article | null>(null);

  // load article detail
  const loadArticleDetailMutation = useMutation({
    mutationFn: async () => {
      dispatch(startLoading({}));
      const res = await articleApi.LoadArticleDetail({ articleId: article.id });
      setArticleDetail(res.data.article);
      return res;
    },
    onSuccess: (data) => {
      dispatch(stopLoading());
      console.log("Get article detail response data:", data);
      if (data && data.errorCode === "0") {
        console.log("Get article detail successful");
      } else {
        console.error("Get article detail failed:", data.message);
      }
    },
    onError: (error: any) => {
      dispatch(stopLoading());
      console.error("Get article detail error:", error.response.data);
    },
  });

  useEffect(() => {
    if (article && article.id) {
      loadArticleDetailMutation.mutate();
    }
  }, [article]);

  if (!article) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <p className="text-xl font-bold mb-4">Article not found</p>
          <Link to="/news" className="text-[#EE0434] font-bold underline">
            Back to News
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-white min-h-screen pb-20">
      <div className="max-w-7xl mx-auto px-4 py-4 md:py-6">
        <nav className="flex items-center flex-wrap gap-2 text-xs md:text-sm text-slate-500 font-medium">
          <Link to="/" className="hover:text-blue-500">
            {t("home")}
          </Link>
          <svg
            className="w-4 h-4"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              d="M9 5l7 7-7 7"
              strokeWidth={2}
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
          <Link to="/news" className="hover:text-blue-500">
            {t("news")}
          </Link>
          <svg
            className="w-4 h-4"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              d="M9 5l7 7-7 7"
              strokeWidth={2}
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
          <span className="text-slate-900 font-bold truncate max-w-[200px] md:max-w-none">
            {article.title}
          </span>
        </nav>
      </div>

      <div className="max-w-7xl mx-auto px-4">
        <header className="py-6 md:py-10 border-t border-slate-50">
          <h1 className="text-2xl md:text-3xl lg:text-4xl font-black text-[#EE0434] leading-tight mb-4">
            {article.title}
          </h1>
          <div className="flex items-center text-slate-400 space-x-2">
            <svg
              className="w-4 h-4"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
              />
            </svg>
            <span className="text-xs md:text-sm font-bold">
              {article.publishedDate}
            </span>
          </div>
        </header>

        <div className="mb-8 md:mb-12">
          <div className="aspect-[21/9] rounded-[24px] md:rounded-[40px] overflow-hidden shadow-2xl">
            <img
              src={articleDetail?.coverImageUrl}
              alt={article.title}
              className="w-full h-full object-cover"
            />
          </div>
        </div>

        <div className="mx-auto">
          <article className="prose prose-lg prose-slate max-w-none text-slate-800">
            <h2 className="text-lg md:text-xl font-black mb-4 text-slate-900 leading-snug">
              {article.title}
            </h2>
            {/* <p className="text-base md:text-lg leading-relaxed mb-4 font-medium text-slate-600"> */}
            {/* show html  */}
            <div
              className="text-slate-600 text-sm md:text-xl leading-relaxed font-medium pb-8"
              dangerouslySetInnerHTML={{ __html: articleDetail?.content || "" }}
            />
            {/* </p> */}
          </article>

          <div className="mt-16 pt-8 border-t border-slate-100 flex flex-col md:flex-row justify-between items-center gap-6">
            <button
              onClick={() => navigate("/news")}
              className="flex items-center space-x-2 text-[#EE0434] font-black hover:translate-x-[-4px] transition-transform text-sm md:text-base"
            >
              <svg
                className="w-4 h-4"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={3}
                  d="M15 19l-7-7 7-7"
                />
              </svg>
              <span>{t("backToNews")}</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ArticleDetailView;
