import { useEffect, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Header } from '../components/Header';
import { ArticleCard } from '../components/ArticleCard';
import { Pagination } from '../components/Pagination';
import { Article } from '../types';
import api from '../utils/api';
import { format, parseISO } from 'date-fns';
import { ru } from 'date-fns/locale';


const ARTICLES_PER_PAGE = 9;

export function SearchPage() {
  const [searchParams, setSearchParams] = useSearchParams();
  const query = searchParams.get('q') || '';
  const authorId = searchParams.get('author') || '';
  const authorName = searchParams.get('authorName') || '';
  const date = searchParams.get('date');
  const currentPage = parseInt(searchParams.get('page') || '1', 10);
  const role = searchParams.get('role') || '';

  const [articles, setArticles] = useState<Article[]>([]);
  const [totalPages, setTotalPages] = useState(1);
  const [totalArticles, setTotalArticles] = useState(0);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const fetchResults = async () => {
      if (!query && !authorId  && !date) return;
      
      setLoading(true);
      try {
        const response = await api.get('/articles/search', {
          params: {
            q: query,
            author: authorId,
            date,
            role: role,
            page: currentPage,
            limit: ARTICLES_PER_PAGE
          }
        });
        setArticles(response.data.articles);
        setTotalPages(response.data.totalPages);
        setTotalArticles(response.data.total);
      } catch (error) {
        console.error('Ошибка поиска:', error);
      } finally {
        setLoading(false);
      }
    };

    window.scrollTo({ top: 0, behavior: 'smooth' });

    fetchResults();
  }, [query, authorId, date, currentPage, role]);

  const handlePageChange = (newPage: number) => {
    setSearchParams({ q: query, page: newPage.toString(), author: authorId, role: role, authorName: authorName });
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const getPageTitle = () => {
    if (authorId) {
      return `Статьи автора ${authorName}`;
    }
    if (date) {
      return `Статьи за ${format(parseISO(date), 'd MMMM, yyyy', { locale: ru })}`;
    }
    return query ? `Результаты поиска "${query}"` : 'Поиск статей';
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <Header />
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        <div className="flex justify-between items-center mb-8">
          <h1 className="text-3xl font-bold text-gray-900">
            {getPageTitle()}
          </h1>
          {articles.length > 0 && (
            <p className="font-bold text-gray-600">
              Статьи {Math.min((currentPage - 1) * ARTICLES_PER_PAGE + 1, totalArticles)}
              -
              {Math.min(currentPage * ARTICLES_PER_PAGE, totalArticles)} из {totalArticles}
            </p>
          )}
        </div>

        {loading ? (
          <div className="flex justify-center items-center h-64">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
          </div>
        ) : articles.length > 0 ? (
          <>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
              {articles.map((article) => (
                <ArticleCard key={article.id} article={article} />
              ))}
            </div>
            {totalPages > 1 && (
              <Pagination
                currentPage={currentPage}
                totalPages={totalPages}
                onPageChange={handlePageChange}
              />
            )}
          </>
        ) : (query || authorId || date) ? (
          <div className="text-center py-12">
            <h2 className="text-xl font-medium text-gray-900 mb-2">
              Не найдено ни одной статьи
            </h2>
            <p className="text-gray-500">
              {authorId ? "Этот автор не опубликовал пока ни одной статьи" :
                  date ? "На эту дату не опубликовано ни одной статьи" :
                      "Ничего не найдено. Попытайтесь изменить сроку поиска"}
            </p>
          </div>
        ) : null}
      </main>
    </div>
  );
}