import React, { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { useLocalizedName } from "@/shared/common/localizedName";
import { useNews } from "@/user-management/web-Management/hooks/useNews";
import { useNewsCategory } from "@/user-management/web-Management/hooks/useNewsCategory";
import { useTheme } from "@/user-management/web-Management/hooks/useTheme";

const FeaturedNews = () => {
  const { t } = useTranslation();
  const localizedName = useLocalizedName();

  const [activeCategory, setActiveCategory] = useState("all");
  const [visibleNews, setVisibleNews] = useState(6);
  const [isMobile, setIsMobile] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const [filterType, setFilterType] = useState("Department");
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [selectedArticle, setSelectedArticle] = useState<any>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);

  const searchParams: Record<string, string> = {};
  if (searchQuery) {
    switch (filterType) {
      case "Department":
        searchParams.sendingPosition = searchQuery;
        break;
      case "Subject":
        searchParams.subject = searchQuery;
        break;
      case "Reference Number":
        searchParams.referenceNumber = searchQuery;
        break;
    }
  }

  const baseParams = { isActive: true };
  const baseParams2 = { isActive: true, isFeatured: true };

  const { items: news, count: newsCount } = useNews(baseParams);
  const { items: featurednews, count: featuredCount } = useNews(baseParams2);
  const { items: newsCategory } = useNewsCategory(baseParams);
  const { items: theme } = useTheme();

  const INITIAL_NEWS_COUNT = 6;
  const LOAD_MORE_COUNT = 3;

  useEffect(() => {
    const checkScreenSize = () => setIsMobile(window.innerWidth < 768);
    checkScreenSize();
    window.addEventListener("resize", checkScreenSize);
    return () => window.removeEventListener("resize", checkScreenSize);
  }, []);

  const loadMoreNews = () => setVisibleNews((prev) => prev + LOAD_MORE_COUNT);
  const showLessNews = () => setVisibleNews(INITIAL_NEWS_COUNT);

  const openArticleModal = (article: any) => {
    setSelectedArticle(article);
    setIsModalOpen(true);
  };

  const closeArticleModal = () => {
    setIsModalOpen(false);
    setSelectedArticle(null);
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    if (isNaN(date.getTime())) return "-";
    return date.toLocaleDateString(undefined, {
      year: "numeric",
      month: "long",
      day: "numeric",
    });
  };

  function lightenColor(color: string, percent: number) {
    const R = parseInt(color.substring(1, 3), 16);
    const G = parseInt(color.substring(3, 5), 16);
    const B = parseInt(color.substring(5, 7), 16);

    const newR = Math.min(255, R + Math.round((255 - R) * (percent / 100)));
    const newG = Math.min(255, G + Math.round((255 - G) * (percent / 100)));
    const newB = Math.min(255, B + Math.round((255 - B) * (percent / 100)));

    return `#${newR.toString(16).padStart(2, "0")}${newG
      .toString(16)
      .padStart(2, "0")}${newB.toString(16).padStart(2, "0")}`;
  }

  const renderArticleContent = (content: string) => {
    if (!content) return null;

    return content.split("\n\n").map((paragraph, index) => (
      <p key={index} className="text-gray-700 leading-relaxed mb-4">
        {paragraph}
      </p>
    ));
  };

  return (
    <>
      <div
        className="min-h-screen py-12 px-4 sm:px-6 lg:px-8"
        style={{
          background: `linear-gradient(
            to bottom,
            ${
              theme?.find((i) => i.type === "PRIMARY_COLOR")?.value
                ? lightenColor(
                    theme.find((i) => i.type === "PRIMARY_COLOR")!.value,
                    30
                  )
                : "var(--primary-300)"
            },
            ${
              theme?.find((i) => i.type === "SECONDARY_COLOR")?.value
                ? lightenColor(
                    theme.find((i) => i.type === "SECONDARY_COLOR")!.value,
                    55
                  )
                : "var(--primary-300)"
            }
          )`,
        }}
      >
        <div className="max-w-7xl mx-auto">
          {/* Header */}
          <div className="text-center mb-12">
            <h1 className="text-4xl md:text-5xl font-bold text-gray-900 mb-4">
              {t("newssection.featuredNews")}
            </h1>
            <p className="text-xl text-gray-600 max-w-3xl mx-auto">
              {t("newssection.description")}
            </p>
            <div className="w-24 h-1 bg-gradient-to-r from-blue-500 to-purple-600 mx-auto mt-6 rounded-full"></div>
          </div>

          {/* Search & Filter */}
          <div className="mb-12 bg-white rounded-2xl shadow-lg p-6">
            <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
              <div className="flex-1 relative">
                <input
                  type="text"
                  placeholder={t("newssection.searchPlaceholder")}
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full pl-12 pr-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-300"
                />
              </div>

              <div className="flex flex-wrap gap-2">
                {newsCategory?.map((category) => (
                  <button
                    key={category.id}
                    onClick={() => {
                      setStatusFilter(category.newsCategoryTitle?.en || "");
                      setVisibleNews(INITIAL_NEWS_COUNT);
                    }}
                    className={`px-4 py-2 rounded-full text-sm font-medium transition-all duration-300 ${
                      activeCategory === category.newsCategoryTitle?.en
                        ? "bg-gradient-to-r from-blue-500 to-purple-600 text-white shadow-lg"
                        : "bg-white text-gray-700 border border-gray-300 hover:border-blue-500"
                    }`}
                  >
                    {localizedName(category.newsCategoryTitle).toUpperCase()}
                  </button>
                ))}
              </div>
            </div>
          </div>

          {/* Featured News */}
          <div className="mb-12">
            <h2 className="text-2xl font-bold text-gray-900 mb-6">
              {t("newssection.topStories")}
            </h2>
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
              {featurednews?.map((article) => (
                <div
                  key={article.id}
                  className="bg-white rounded-2xl shadow-lg overflow-hidden transition-all duration-300 hover:shadow-xl group"
                >
                  <div className="relative overflow-hidden">
                    <img
                      src={article.presigned}
                      alt={localizedName(article.title)}
                      className="w-full h-64 object-cover transition-transform duration-500 group-hover:scale-110"
                    />
                    <div className="absolute top-4 left-4">
                      <span
                        className="px-3 py-1 rounded-full text-xs font-semibold"
                        style={{
                          backgroundColor: article.newsCategory?.color || "",
                        }}
                      >
                        {localizedName(article.newsCategory?.newsCategoryTitle)}
                      </span>
                    </div>
                    <div className="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent"></div>
                    <div className="absolute bottom-4 left-4 right-4 text-white">
                      <h3 className="text-xl font-bold mb-2 line-clamp-2">
                        {localizedName(article?.title)}
                      </h3>
                      <div className="flex items-center text-sm text-gray-200">
                        <span>{formatDate(article?.createdAt)}</span>
                      </div>
                    </div>
                  </div>
                  <div className="p-6">
                    <p className="text-gray-600 mb-4 line-clamp-3">
                      {localizedName(article?.subTitle)}
                    </p>
                    <button
                      onClick={() => openArticleModal(article)}
                      className="text-blue-600 font-semibold hover:text-blue-700 transition-colors flex items-center"
                    >
                      {t("newssection.readFullStory")}
                      <svg
                        className="ml-1 w-4 h-4"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2}
                          d="M9 5l7 7-7 7"
                        />
                      </svg>
                    </button>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* News Grid */}
          <div className="mb-12">
            <h2 className="text-2xl font-bold text-gray-900 mb-6">
              {activeCategory === "all"
                ? t("newssection.allNews")
                : `${
                    activeCategory.charAt(0).toUpperCase() +
                    activeCategory.slice(1)
                  } ${t("newssection.allNews")}`}
              <span className="text-gray-500 text-lg ml-2">({newsCount})</span>
            </h2>

            {newsCount === 0 ? (
              <div className="text-center py-12">
                <h3 className="text-xl font-semibold text-gray-600 mb-2">
                  {t("newssection.noNewsFound")}
                </h3>
                <p className="text-gray-500">
                  {t("newssection.noNewsFoundDesc")}
                </p>
              </div>
            ) : (
              <>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  {news?.slice(0, visibleNews).map((article) => (
                    <div
                      key={article.id}
                      className="bg-white rounded-xl shadow-md overflow-hidden transition-all duration-300 hover:shadow-lg hover:scale-105 group"
                    >
                      <div className="relative overflow-hidden">
                        <img
                          src={article.presigned}
                          alt={localizedName(article?.title)}
                          className="w-full h-48 object-cover transition-transform duration-500 group-hover:scale-110"
                        />
                        <div className="absolute top-3 left-3">
                          <span
                            className="px-3 py-1 rounded-full text-xs font-semibold"
                            style={{
                              backgroundColor:
                                article.newsCategory?.color || "var(--primary-100)",
                            }}
                          >
                            {localizedName(
                              article?.newsCategory?.newsCategoryTitle
                            )}
                          </span>
                        </div>
                      </div>
                      <div className="p-5">
                        <div className="flex items-center text-sm text-gray-500 mb-2">
                          <span>{formatDate(article.updatedAt)}</span>
                        </div>
                        <h3 className="text-lg font-bold text-gray-900 mb-2 line-clamp-2 group-hover:text-blue-600 transition-colors">
                          {localizedName(article.title)}
                        </h3>
                        <p className="text-gray-600 text-sm mb-4 line-clamp-3">
                          {localizedName(article?.subTitle)}
                        </p>
                        <button
                          onClick={() => openArticleModal(article)}
                          className="text-blue-600 text-sm font-semibold hover:text-blue-700 transition-colors flex items-center"
                        >
                          {t("newssection.readMore")}
                          <svg
                            className="ml-1 w-3 h-3"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                          >
                            <path
                              strokeLinecap="round"
                              strokeLinejoin="round"
                              strokeWidth={2}
                              d="M9 5l7 7-7 7"
                            />
                          </svg>
                        </button>
                      </div>
                    </div>
                  ))}
                </div>

                {(newsCount || 0) > INITIAL_NEWS_COUNT && (
                  <div className="text-center mt-8 flex justify-center gap-4">
                    {visibleNews < (newsCount || 0) && (
                      <button
                        onClick={loadMoreNews}
                        className="bg-gradient-to-r from-blue-500 to-purple-600 text-white px-8 py-3 rounded-xl font-semibold hover:shadow-lg transition-all duration-300 transform hover:scale-105"
                      >
                        {t("newssection.loadMoreNews")} (
                        {(newsCount || 0) - visibleNews} remaining)
                      </button>
                    )}
                    {visibleNews > INITIAL_NEWS_COUNT && (
                      <button
                        onClick={showLessNews}
                        className="bg-gray-200 text-gray-700 px-8 py-3 rounded-xl font-semibold hover:bg-gray-300 transition-all duration-300 transform hover:scale-105"
                      >
                        {t("newssection.showLess")}
                      </button>
                    )}
                  </div>
                )}
              </>
            )}
          </div>
        </div>
      </div>

      {/* News Article Modal */}
      {isModalOpen && selectedArticle && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
          <div className="bg-white rounded-2xl shadow-2xl max-w-4xl w-full max-h-[90vh] overflow-hidden flex flex-col">
            {/* Modal Header */}
            <div className="relative">
              <img
                src={selectedArticle.presigned}
                alt={localizedName(selectedArticle.title)}
                className="w-full h-64 object-cover"
              />
              <div className="absolute top-4 left-4">
                <span
                  className="px-3 py-1 rounded-full text-xs font-semibold text-white"
                  style={{
                    backgroundColor:
                      selectedArticle.newsCategory?.color || "rgba(0,0,0,0.7)",
                  }}
                >
                  {localizedName(
                    selectedArticle.newsCategory?.newsCategoryTitle
                  )}
                </span>
              </div>
              <button
                onClick={closeArticleModal}
                className="absolute top-4 right-4 text-white bg-black/50 hover:bg-black/70 rounded-full p-2 transition-colors duration-200"
              >
                <svg
                  className="w-6 h-6"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M6 18L18 6M6 6l12 12"
                  />
                </svg>
              </button>
              <div className="absolute bottom-4 left-4 right-4 text-white">
                <h2 className="text-2xl md:text-3xl font-bold mb-2">
                  {localizedName(selectedArticle.title)}
                </h2>
                <div className="flex items-center text-sm text-gray-200">
                  <span>{formatDate(selectedArticle.createdAt)}</span>
                </div>
              </div>
            </div>

            {/* Modal Content */}
            <div className="p-6 overflow-y-auto custom-scrollbar flex-1">
              <div className="prose prose-lg max-w-none">
                <h3 className="text-xl font-semibold text-gray-800 mb-4">
                  {localizedName(selectedArticle.subTitle)}
                </h3>
                {renderArticleContent(
                  localizedName(selectedArticle.content) ||
                    localizedName(selectedArticle.subTitle)
                )}

                {/* Additional article details */}
                <div className="mt-8 pt-6 border-t border-gray-200">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm text-gray-600">
                    <div>
                      <span className="font-semibold">Published: </span>
                      {formatDate(selectedArticle.createdAt)}
                    </div>
                    <div>
                      <span className="font-semibold">Last Updated: </span>
                      {formatDate(selectedArticle.updatedAt)}
                    </div>
                    {selectedArticle.referenceNumber && (
                      <div>
                        <span className="font-semibold">Reference: </span>
                        {selectedArticle.referenceNumber}
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </div>

            {/* Modal Footer */}
            <div className="border-t border-gray-200 bg-gray-50 flex-shrink-0">
              <div className="p-4 text-center">
                <button
                  onClick={closeArticleModal}
                  className="px-6 py-2 border border-gray-300 text-base font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors duration-200"
                >
                  {t("preview.close") || "Close"}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default FeaturedNews;
