import React, { useState, useMemo, useEffect } from 'react';
import { Author, AuthorRole } from '../types';
import { X, ChevronLeft, ChevronRight, Search } from 'lucide-react';
import { CSSTransition, TransitionGroup } from 'react-transition-group';

interface AuthorSelectionModalProps {
  isOpen: boolean;
  onClose: () => void;
  onAddAuthor: (authorId: string, role: AuthorRole) => void;
  authors: Author[];
  existingAuthors: { authorId: string; role: AuthorRole }[];
}

const roleLabels: Record<AuthorRole, string> = {
  WRITER: 'Авторы',
  PHOTOGRAPHER: 'Фотографы',
  EDITOR: 'Редакторы',
  TRANSLATOR: 'Переводчики',
};

const AuthorSelectionModal: React.FC<AuthorSelectionModalProps> = ({
                                                                     isOpen,
                                                                     onClose,
                                                                     onAddAuthor,
                                                                     authors,
                                                                     existingAuthors,
                                                                   }) => {
  const [activeTab, setActiveTab] = useState<AuthorRole>(AuthorRole.WRITER);
  const [currentPage, setCurrentPage] = useState(1);
  const [searchTerm, setSearchTerm] = useState('');
  const itemsPerPage = 6;

  // Обработчик нажатия клавиши Esc
  useEffect(() => {
    const handleEscKey = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        onClose();
      }
    };

    if (isOpen) {
      document.addEventListener('keydown', handleEscKey);
    }

    return () => {
      document.removeEventListener('keydown', handleEscKey);
    };
  }, [isOpen, onClose]);

  // Используем useMemo для оптимальной фильтрации и сортировки авторов
  const { popularAuthors, otherAuthors } = useMemo(() => {
    // Фильтруем авторов по активной вкладке и исключаем уже добавленных
    const filteredAuthors = authors.filter(author =>
        author.roles.includes(activeTab) &&
        !existingAuthors.some(existing => existing.authorId === author.id && existing.role === activeTab)
    );

    // Сортируем по полю order (по возрастанию) и берем первые 5
    const sortedByOrder = [...filteredAuthors].sort((a, b) => a.order - b.order);
    const popularAuthors = sortedByOrder.slice(0, 6);

    // Остальных авторов сортируем по алфавиту
    const otherAuthors = filteredAuthors
        .filter(author => !popularAuthors.includes(author))
        .sort((a, b) => a.displayName.localeCompare(b.displayName, 'ru'));

    return { popularAuthors, otherAuthors };
  }, [authors, existingAuthors, activeTab]);

  // Получаем уникальные первые буквы имен остальных авторов
  const firstLetters = useMemo(() => {
    const letters = new Set<string>();

    otherAuthors.forEach(author => {
      // Берем первую букву имени, приводим к верхнему регистру
      const firstLetter = author.displayName.charAt(0).toUpperCase();
      letters.add(firstLetter);
    });

    // Преобразуем Set в массив и сортируем
    return Array.from(letters).sort();
  }, [otherAuthors]);

  // Фильтруем остальных авторов по поисковому запросу
  const filteredOtherAuthors = useMemo(() => {
    if (!searchTerm.trim()) {
      return otherAuthors;
    }

    const searchLower = searchTerm.toLowerCase().trim();
    return otherAuthors.filter(author =>
        author.displayName.toLowerCase().startsWith(searchLower)
    );
  }, [otherAuthors, searchTerm]);

  // Вычисляем данные для пагинации только для отфильтрованных остальных авторов
  const paginationData = useMemo(() => {
    const totalAuthors = filteredOtherAuthors.length;
    const totalPages = Math.ceil(totalAuthors / itemsPerPage);
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    const displayedOtherAuthors = filteredOtherAuthors.slice(startIndex, endIndex);

    return {
      totalAuthors,
      totalPages,
      displayedOtherAuthors,
      showPagination: totalPages > 1
    };
  }, [filteredOtherAuthors, currentPage, itemsPerPage]);

  // Сбрасываем страницу при изменении поискового запроса
  useEffect(() => {
    setCurrentPage(1);
  }, [searchTerm]);

  // Обработчик выбора автора
  const handleAuthorSelect = (authorId: string) => {
    onAddAuthor(authorId, activeTab);
    onClose();
  };

  const handleTabChange = (role: AuthorRole) => {
    setActiveTab(role);
    setCurrentPage(1);
    setSearchTerm('');
  };

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
    // Прокручиваем к началу списка остальных авторов
    document.getElementById('other-authors-section')?.scrollIntoView({ behavior: 'smooth' });
  };

  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchTerm(e.target.value);
  };

  const clearSearch = () => {
    setSearchTerm('');
  };

  const handleLetterClick = (letter: string) => {
    setSearchTerm(letter.toLowerCase());
  };

  if (!isOpen) return null;

  const { totalAuthors, totalPages, displayedOtherAuthors, showPagination } = paginationData;

  return (
      <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
        <div className="bg-white rounded-lg shadow-xl w-full max-w-4xl max-h-[90vh] flex flex-col">
          {/* Заголовок */}
          <div className="flex justify-between items-center p-6 border-b">
            <h2 className="text-xl font-bold">Добавить автора</h2>
            <button
                onClick={onClose}
                className="text-gray-500 hover:text-gray-700"
            >
              <X size={24} />
            </button>
          </div>

          {/* Вкладки */}
          <div className="flex border-b">
            {Object.entries(roleLabels).map(([role, label]) => {
              const roleAuthorsCount = authors.filter(author =>
                  author.roles.includes(role as AuthorRole) &&
                  !existingAuthors.some(existing => existing.authorId === author.id && existing.role === role)
              ).length;

              return (
                  <button
                      key={role}
                      className={`px-6 py-3 font-medium text-sm flex items-center ${
                          activeTab === role
                              ? 'text-blue-600 border-b-2 border-blue-600'
                              : 'text-gray-500 hover:text-gray-700'
                      }`}
                      onClick={() => handleTabChange(role as AuthorRole)}
                  >
                    {label}
                    {roleAuthorsCount > 0 && (
                        <span className="ml-2 bg-gray-200 text-gray-700 text-xs px-2 py-0.5 rounded-full">
                    {roleAuthorsCount}
                  </span>
                    )}
                  </button>
              );
            })}
          </div>

          {/* Содержимое вкладки */}
          <div className="flex-1 overflow-y-auto p-6">
            {/* Популярные авторы (всегда отображаются, если есть) */}
            {popularAuthors.length > 0 && (
                <div key={`popular-${activeTab}`} className="mb-8">
                  <div className="flex items-center mb-4">
                    <h3 className="text-lg font-semibold text-gray-700">Популярные</h3>
                    <span className="ml-2 px-2 py-1 bg-blue-100 text-blue-800 text-xs font-medium rounded-full">
                  По рейтингу
                </span>
                  </div>
                  <TransitionGroup className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {popularAuthors.map(author => (
                        <CSSTransition
                            key={`${author.id}-${activeTab}`}
                            timeout={300}
                            classNames="author-card"
                        >
                          <AuthorCard
                              key={author.id}
                              author={author}
                              onSelect={() => handleAuthorSelect(author.id)}
                              showOrder={true}
                          />
                        </CSSTransition>
                    ))}
                  </TransitionGroup>
                </div>
            )}

            {/* Все остальные авторы с поиском и пагинацией */}
            <div id="other-authors-section" key={`other-${activeTab}`}>
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-lg font-semibold text-gray-700">
                  Остальные {roleLabels[activeTab].toLowerCase()}
                </h3>
                <div className="flex items-center space-x-4">
                <span className="text-sm text-gray-500">
                  Всего: {totalAuthors}
                </span>
                  {showPagination && (
                    <span className="text-sm text-gray-500">
                     Страница {currentPage} из {totalPages}
                    </span>
                  )}
                </div>
              </div>

              {/* Кнопки с первыми буквами */}
              {firstLetters.length > 0 && (
                  <div className="mb-4">
                    <div className="flex flex-wrap gap-2">
                      <button
                          onClick={clearSearch}
                          className={`px-3 py-1.5 text-sm rounded-full ${
                              searchTerm === ''
                                  ? 'bg-blue-600 text-white'
                                  : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
                          }`}
                      >
                        Все
                      </button>
                      {firstLetters.map(letter => (
                          <button
                              key={letter}
                              onClick={() => handleLetterClick(letter)}
                              className={`px-3 py-1.5 text-sm rounded-full ${
                                  searchTerm.toLowerCase() === letter.toLowerCase()
                                      ? 'bg-blue-600 text-white'
                                      : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
                              }`}
                          >
                            {letter}
                          </button>
                      ))}
                    </div>
                  </div>
              )}

              {/* Поле поиска */}
              <div className="mb-6">
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <Search size={20} className="text-gray-400" />
                  </div>
                  <input
                      type="text"
                      placeholder="Поиск по имени..."
                      className="w-full pl-10 pr-10 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      value={searchTerm}
                      onChange={handleSearchChange}
                  />
                  {searchTerm && (
                      <button
                          onClick={clearSearch}
                          className="absolute inset-y-0 right-0 pr-3 flex items-center"
                      >
                        <X size={20} className="text-gray-400 hover:text-gray-600" />
                      </button>
                  )}
                </div>
                {searchTerm && (
                    <p className="mt-2 text-sm text-gray-500">
                      Найдено: {totalAuthors} {totalAuthors === 1 ? 'автор' : 'авторов'}
                    </p>
                )}
              </div>

              {displayedOtherAuthors.length > 0 ? (
                  <>
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                      {displayedOtherAuthors.map(author => (
                          <AuthorCard
                              key={author.id}
                              author={author}
                              onSelect={() => handleAuthorSelect(author.id)}
                              showOrder={false}
                          />
                      ))}
                    </div>

                    {/* Пагинация */}
                    {showPagination && (
                        <div className="flex justify-center mt-8">
                          <div className="flex items-center space-x-2">
                            <button
                                onClick={() => handlePageChange(currentPage - 1)}
                                disabled={currentPage === 1}
                                className={`p-2 rounded-full ${
                                    currentPage === 1
                                        ? 'text-gray-300 cursor-not-allowed'
                                        : 'text-gray-600 hover:bg-gray-100'
                                }`}
                            >
                              <ChevronLeft size={20} />
                            </button>

                            {Array.from({ length: totalPages }, (_, i) => i + 1).map(page => (
                                <button
                                    key={page}
                                    onClick={() => handlePageChange(page)}
                                    className={`w-10 h-10 rounded-full ${
                                        currentPage === page
                                            ? 'bg-blue-600 text-white'
                                            : 'text-gray-600 hover:bg-gray-100'
                                    }`}
                                >
                                  {page}
                                </button>
                            ))}

                            <button
                                onClick={() => handlePageChange(currentPage + 1)}
                                disabled={currentPage === totalPages}
                                className={`p-2 rounded-full ${
                                    currentPage === totalPages
                                        ? 'text-gray-300 cursor-not-allowed'
                                        : 'text-gray-600 hover:bg-gray-100'
                                }`}
                            >
                              <ChevronRight size={20} />
                            </button>
                          </div>
                        </div>
                    )}
                  </>
              ) : (
                  <p className="text-gray-500 text-center py-8">
                    {searchTerm
                        ? `Нет авторов, начинающихся с "${searchTerm}"`
                        : `Нет доступных ${roleLabels[activeTab].toLowerCase()}`
                    }
                  </p>
              )}
            </div>
          </div>
        </div>
      </div>
  );
};

// Обновленный компонент карточки автора
interface AuthorCardProps {
  author: Author;
  onSelect: () => void;
  showOrder: boolean;
}

const AuthorCard: React.FC<AuthorCardProps> = ({ author, onSelect, showOrder }) => {
  return (
      <div
          className={`border rounded-lg p-4 cursor-pointer transition-all hover:border-blue-500 hover:bg-blue-50 hover:shadow-md ${
              showOrder ? 'border-gray-200' : 'border-gray-200'
          }`}
          onClick={onSelect}
      >
        <div className="flex items-center">
          {author.avatarUrl ? (
              <img
                  src={author.avatarUrl}
                  alt={author.displayName}
                  className="w-12 h-12 rounded-full object-cover mr-3"
              />
          ) : (
              <div className="w-12 h-12 rounded-full bg-gray-200 flex items-center justify-center mr-3">
            <span className="text-gray-500 font-medium">
              {author.displayName.charAt(0)}
            </span>
              </div>
          )}
          <div className="flex-1">
            <div className="flex items-center justify-between">
              <h4 className="font-medium text-gray-900">{author.displayName}</h4>
              {showOrder && (
                  <span className="text-xs font-medium bg-blue-100 text-blue-800 px-2 py-1 rounded-full">
                #{author.order}
              </span>
              )}
            </div>
            {author.email && (
                <p className="text-sm text-gray-500">{author.email}</p>
            )}
          </div>
        </div>
      </div>
  );
};

export default AuthorSelectionModal;