import React, { useState } from 'react';
import useArtists from '../hooks/useArtists';
import ArtistList from '../components/ArtistList';
import { Artist, Epoch, Country } from '../types';

const ArtistsPage: React.FC = () => {
  const { artists, loading, error, removeArtist, editArtist, epochs, countries, sortOrder } = useArtists();
  const [editingArtist, setEditingArtist] = useState<Artist | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [sortConfig, setSortConfig] = useState<{ field: 'name' | 'epoch' | 'country'; direction: 'asc' | 'desc' }>({
    field: 'name',
    direction: 'asc'
  });

  // Константы для пагинации
  const artistsPerPage = 6;
  const indexOfLastArtist = currentPage * artistsPerPage;
  const indexOfFirstArtist = indexOfLastArtist - artistsPerPage;

  
  const sortedArtists = [...artists].sort((a, b) => {
    const getFieldValue = (artist: Artist) => {
      if (sortConfig.field === 'name') return artist.name;
      if (sortConfig.field === 'epoch') return artist.epoch?.name || '';
      return artist.country?.name || '';
    };

    const valueA = getFieldValue(a);
    const valueB = getFieldValue(b);

    if (valueA < valueB) return sortConfig.direction === 'asc' ? -1 : 1;
    if (valueA > valueB) return sortConfig.direction === 'asc' ? 1 : -1;
    return 0;
  });

  // Текущие артисты для отображения
  const currentArtists = sortedArtists.slice(indexOfFirstArtist, indexOfLastArtist);

  if (loading) return <p className="text-center text-punk my-5">Загрузка...</p>;
  if (error) return <p className="text-center text-danger my-5">Ошибка: {error}</p>;

  const handleEdit = (artist: Artist) => {
    setEditingArtist(artist);
  };

  const handleDelete = (id: string) => {
    removeArtist(id);
    // Сброс страницы при удалении
    if (currentArtists.length === 1 && currentPage > 1) {
      setCurrentPage(currentPage - 1);
    }
  };

  const handleSave = async () => {
    if (editingArtist) {
      await editArtist(editingArtist.id, editingArtist);
      setEditingArtist(null);
    }
  };

  const toggleSort = (field: 'name' | 'epoch' | 'country') => {
    setSortConfig(prev => ({
      field,
      direction: prev.field === field && prev.direction === 'asc' ? 'desc' : 'asc'
    }));
  };

  const paginate = (pageNumber: number) => setCurrentPage(pageNumber);

  return (
    <div className="container py-4">
      <h1 className="text-punk mb-3">Список исполнителей</h1>

      {/* Кнопки сортировки */}
      <div className="d-flex gap-2 mb-3">
        <button 
          className={`btn btn-outline-punk text-light ${sortConfig.field === 'name' ? 'active' : ''}`}
          onClick={() => toggleSort('name')}
        >
          По имени {sortConfig.field === 'name' && (sortConfig.direction === 'asc' ? '↑' : '↓')}
        </button>
        <button 
          className={`btn btn-outline-punk text-light ${sortConfig.field === 'epoch' ? 'active' : ''}`}
          onClick={() => toggleSort('epoch')}
        >
          По эпохе {sortConfig.field === 'epoch' && (sortConfig.direction === 'asc' ? '↑' : '↓')}
        </button>
        <button 
          className={`btn btn-outline-punk text-light ${sortConfig.field === 'country' ? 'active' : ''}`}
          onClick={() => toggleSort('country')}
        >
          По стране {sortConfig.field === 'country' && (sortConfig.direction === 'asc' ? '↑' : '↓')}
        </button>
      </div>

      <ArtistList artists={currentArtists} onEdit={handleEdit} onDelete={handleDelete} epochs={epochs} countries={countries} />

      {/* Пагинация */}
      <nav className="mt-4">
        <ul className="pagination justify-content-center">
          {Array.from({ length: Math.ceil(artists.length / artistsPerPage) }).map((_, index) => (
            <li key={index} className={`page-item ${currentPage === index + 1 ? 'active' : ''}`}>
              <button
                className="page-link bg-dark text-punk border-punk"
                onClick={() => paginate(index + 1)}
              >
                {index + 1}
              </button>
            </li>
          ))}
        </ul>
      </nav>

      {/* Модальное окно редактирования */}
      {editingArtist && (
        <div className="modal show" style={{ display: 'block', backgroundColor: 'rgba(0,0,0,0.7)' }}>
          <div className="modal-dialog modal-dialog-centered">
            <div className="modal-content bg-dark border-punk">
              <div className="modal-header">
                <h5 className="modal-title text-punk">Редактировать исполнителя</h5>
                <button
                  type="button"
                  className="btn-close btn-close-white"
                  onClick={() => setEditingArtist(null)}
                ></button>
              </div>
              <div className="modal-body">
                <div className="mb-3">
                  <label className="form-label text-light">Имя</label>
                  <input
                    type="text"
                    className="form-control bg-dark text-light border-punk"
                    value={editingArtist.name}
                    onChange={(e) => setEditingArtist({...editingArtist, name: e.target.value})}
                  />
                </div>
                <div className="mb-3">
                  <label className="form-label text-light">Описание</label>
                  <textarea
                    className="form-control bg-dark text-light border-punk"
                    value={editingArtist.description}
                    onChange={(e) => setEditingArtist({...editingArtist, description: e.target.value})}
                  />
                </div>
              </div>
              <div className="modal-footer">
                <button
                  className="btn btn-secondary"
                  onClick={() => setEditingArtist(null)}
                >
                  Отмена
                </button>
                <button
                  className="btn btn-punk"
                  onClick={handleSave}
                >
                  Сохранить
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ArtistsPage;