import React from "react";
import { useNavigate, Link } from "react-router-dom";
import { NewsArticle } from "../../services/types";
import { DataCacheKey, staleTime } from "../../global/constants";
import { useQuery } from "@tanstack/react-query";
import { Article, Category } from "../../services/article/types";
import { startLoading, stopLoading } from "../../features/loading/loadingSlice";
import { useAppDispatch } from "../../hooks/useRedux";
import { articleApi } from "../../apis/articleApi";
import { useTranslation } from "react-i18next";

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

  const { data: loadArticleData = [] } = useQuery<Article[]>({
    queryKey: [DataCacheKey.ARTICLES],
    queryFn: async (): Promise<Article[]> => {
      try {
        dispatch(startLoading({}));
        const res = await articleApi.LoadArticle({
          pageNumber: 0,
          pageSize: 10,
          categoryId: null,
          isFeatured: true,
        });
        console.log("Loaded articles: ", res.data.articles);
        return res.data.articles as Article[];
      } catch (error) {
        console.error(error);
        return []; // 🔴 bắt buộc
      } finally {
        dispatch(stopLoading());
      }
    },
    staleTime: staleTime,
  });

  const handleArticleClick = (article: Article) => {
    navigate(`/news/${article.id}`, { state: { article } });
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  return (
    <div className="bg-[#fcfdfe] min-h-screen">
      <div className="max-w-7xl mx-auto px-4 py-4 md:py-6 border-b border-slate-50">
        <nav className="flex items-center space-x-2 text-xs md:text-sm text-slate-500 font-medium">
          <Link to="/" className="hover:text-blue-500 text-[18px]">
            {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>
          <span className="text-slate-900 font-bold text-[18px]">
            {t("news")}
          </span>
        </nav>
      </div>

      <div className="max-w-7xl mx-auto px-4 py-12">
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 md:gap-8">
          {loadArticleData.map((article) => (
            <div
              key={article.id}
              onClick={() => handleArticleClick(article)}
              className="bg-white rounded-[24px] overflow-hidden shadow-sm hover:shadow-xl transition-all duration-300 flex flex-col group cursor-pointer border border-slate-50"
            >
              <div className="relative aspect-[4/3] overflow-hidden">
                <img
                  src={article.thumbnailUrl}
                  alt={article.title}
                  className="w-full h-full object-cover transition-transform duration-700 group-hover:scale-110"
                />
              </div>
              <div className="p-6 flex flex-col flex-1 space-y-3">
                <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 font-bold">
                    {article.publishedDate}
                  </span>
                </div>
                <h3 className="text-[16px] md:text-[18px] font-black text-slate-800 leading-tight group-hover:text-[#EE0434] transition-colors line-clamp-3">
                  {article.title}
                </h3>
                <p className="text-xs md:text-sm text-slate-500 font-medium line-clamp-3 leading-relaxed">
                  {article.summary}
                </p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default NewsView;
