import { useEffect, useMemo, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { ArticleCard } from './ArticleCard';
import { Pagination } from './Pagination';
import {Article, CategoryTitles, CityTitles} from '../types';
import axios from "axios";

const ARTICLES_PER_PAGE = 6;

export function FeaturedSection() {
//  const location = useLocation();
  const [searchParams, setSearchParams] = useSearchParams();
  const category = searchParams.get('category');
  const city = searchParams.get('city');
  const currentPage = parseInt(searchParams.get('page') || '1', 10);

  const [articles, setArticles] = useState<Article[]>([]);
  const [error, setError] = useState<string | null>(null);

  // Загрузка статей с backend
  useEffect(() => {
    const fetchArticles = async () => {
      try {
        const response = await axios.get('/api/articles/', {
          params: {
            page: currentPage,
            categoryId: category || undefined,
            cityId: city || undefined,
          },
        });
        console.log('Загруженные данные:', response.data);
        setArticles(response.data.articles);
      } catch (error) {
        setError('Не удалось загрузить статьи');
        console.error(error);
      }
    };

    fetchArticles();
  }, [category, city, currentPage]);

  // Фильтрация статей
  const filteredArticles = useMemo(() => {
    return articles.filter(article => {

      if (category && city) {
        return article.categoryId === Number(category) && article.cityId === Number(city);
      }

      if (category) {
        return article.categoryId === Number(category);
      }

      if (city) {
        return article.cityId === Number(city);
      }

      return true;
    });
  }, [articles, category, city]);

  const totalPages = Math.ceil(filteredArticles.length / ARTICLES_PER_PAGE);
  
  const currentArticles = useMemo(() => {
    const startIndex = (currentPage - 1) * ARTICLES_PER_PAGE;
    return filteredArticles.slice(startIndex, startIndex + ARTICLES_PER_PAGE);
  }, [filteredArticles, currentPage]);

  const handlePageChange = (page: number) => {
    searchParams.set('page', page.toString());
    setSearchParams(searchParams);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  if (filteredArticles.length === 0) {
    return (
      <section className="py-12 px-4 sm:px-6 lg:px-8 max-w-7xl mx-auto">
        <div className="text-center py-12">
          <h3 className="text-xl font-medium text-gray-900 mb-2">
            Еще нет заметок
          </h3>
          <p className="text-gray-500">
            Выберите другой раздел или город
          </p>
        </div>
      </section>
    );
  }

  return (
    <section className="py-12 px-4 sm:px-6 lg:px-8 max-w-7xl mx-auto">
      <div className="flex justify-between items-center mb-8">
        <h2 className="text-3xl font-bold text-gray-900">
          {city ? `${CityTitles[Number(city)]} ` : ''}
          {category ? `${CategoryTitles[Number(category)]} Статьи` : 'Тематические статьи'}
        </h2>
        <p className="text-gray-600">
          Показано {Math.min(currentPage * ARTICLES_PER_PAGE, filteredArticles.length)} из {filteredArticles.length} статей
        </p>
      </div>

      {error && (
          <div className="mb-6 bg-red-50 text-red-700 p-4 rounded-md">
            {error}
          </div>
      )}

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
        {currentArticles.map((article, index) => (
          <ArticleCard
            key={article.id}
            article={article}
            featured={currentPage === 1 && index === 0 && !category && !city}
          />
        ))}
      </div>

      {totalPages > 1 && (
        <Pagination
          currentPage={currentPage}
          totalPages={totalPages}
          onPageChange={handlePageChange}
        />
      )}
    </section>
  );
}