import React, { useState, useEffect } from 'react';
import Header from '../components/Header';
import Footer from '../components/Footer';
import ArtistList from '../components/ArtistList';
import ArtistForm from '../components/ArtistForm';
import { getArtists, getCountries, getEpochs, createArtist, updateArtist, deleteArtist } from '../services/api';

const PunkRockPage = () => {
  const [artists, setArtists] = useState([]);
  const [countries, setCountries] = useState([]);
  const [epochs, setEpochs] = useState([]);
  const [loading, setLoading] = useState(true);
  const [editingArtist, setEditingArtist] = useState(null);
  const [sortDirection, setSortDirection] = useState('asc'); // 'asc' для А-Я, 'desc' для Я-А

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [artistsData, countriesData, epochsData] = await Promise.all([
          getArtists(),
          getCountries(),
          getEpochs()
        ]);
        console.log('Fetched Artists:', artistsData);
        console.log('Fetched Countries:', countriesData);
        console.log('Fetched Epochs:', epochsData);
        setArtists(artistsData);
        setCountries(countriesData.map(country => ({
          ...country,
          id: parseInt(country.id)
        })));
        setEpochs(epochsData.map(epoch => ({
          ...epoch,
          id: parseInt(epoch.id)
        })));
        setLoading(false);
      } catch (error) {
        console.error('Error fetching data:', error);
        setLoading(false);
      }
    };
    fetchData();
  }, []);

  const handleAddArtist = async (artistData) => {
    try {
      // Проверка уникальности имени
      const isDuplicate = artists.some(artist => artist.name.toLowerCase() === artistData.name.toLowerCase());
      if (isDuplicate) {
        alert('Исполнитель с таким именем уже существует!');
        return;
      }

      const newArtist = await createArtist(artistData);
      console.log('Added Artist:', newArtist);
      setArtists(prevArtists => {
        const enrichedArtist = {
          ...newArtist,
          epoch: epochs.find(epoch => epoch.id === parseInt(newArtist.epochId)),
          country: countries.find(country => country.id === parseInt(newArtist.countryId))
        };
        return [...prevArtists, enrichedArtist].sort((a, b) => 
          sortDirection === 'asc' ? a.name.localeCompare(b.name) : b.name.localeCompare(a.name)
        );
      });
    } catch (error) {
      console.error('Error adding artist:', error);
      throw error;
    }
  };

  const handleUpdateArtist = async (artistData) => {
    try {
      // Проверка уникальности имени (кроме текущего исполнителя)
      const isDuplicate = artists.some(artist => 
        artist.name.toLowerCase() === artistData.name.toLowerCase() && artist.id !== editingArtist.id
      );
      if (isDuplicate) {
        alert('Исполнитель с таким именем уже существует!');
        return;
      }

      const updatedArtist = await updateArtist(editingArtist.id, artistData);
      console.log('Updated Artist:', updatedArtist);
      setArtists(prevArtists => {
        const enrichedArtist = {
          ...updatedArtist,
          epoch: epochs.find(epoch => epoch.id === parseInt(updatedArtist.epochId)),
          country: countries.find(country => country.id === parseInt(updatedArtist.countryId))
        };
        return prevArtists.map(a => (a.id === updatedArtist.id ? enrichedArtist : a))
          .sort((a, b) => 
            sortDirection === 'asc' ? a.name.localeCompare(b.name) : b.name.localeCompare(a.name)
          );
      });
      setEditingArtist(null);
    } catch (error) {
      console.error('Error updating artist:', error);
      throw error;
    }
  };

  const handleDeleteArtist = async (id) => {
    try {
      await deleteArtist(id);
      setArtists(artists.filter(artist => artist.id !== id)
        .sort((a, b) => 
          sortDirection === 'asc' ? a.name.localeCompare(b.name) : b.name.localeCompare(a.name)
        ));
    } catch (error) {
      console.error('Error deleting artist:', error);
      throw error;
    }
  };

  const toggleSortDirection = () => {
    setSortDirection(prev => prev === 'asc' ? 'desc' : 'asc');
  };

  if (loading) {
    return <div className="text-center text-punk my-5">Загрузка...</div>;
  }

  const enrichedArtists = artists.map(artist => ({
    ...artist,
    epoch: epochs.find(epoch => epoch.id === parseInt(artist.epochId)),
    country: countries.find(country => country.id === parseInt(artist.countryId))
  })).sort((a, b) => 
    sortDirection === 'asc' ? a.name.localeCompare(b.name) : b.name.localeCompare(a.name)
  );

  return (
    <>
      <Header />
      <main className="container-fluid my-5 flex-grow-1">
        <div className="container py-4">
          <div className="card bg-dark border-punk mb-4">
            <div className="card-body">
              <h3 className="text-punk mb-3">
                <i className="bi bi-people-fill"></i> Перечень исполнителей панк-рока
              </h3>
              <p className="lead text-light">
                Список культовых групп жанра
              </p>
              <button 
                className="btn btn-outline-secondary mb-3" 
                onClick={toggleSortDirection}
              >
                Сортировать {sortDirection === 'asc' ? 'А-Я' : 'Я-А'}
              </button>
              <ArtistList 
                artists={enrichedArtists} 
                onEdit={setEditingArtist} 
                onDelete={handleDeleteArtist} 
              />
            </div>
          </div>
        </div>

        <div className="container my-5">
          <ArtistForm 
            countries={countries} 
            epochs={epochs} 
            onSubmit={editingArtist ? handleUpdateArtist : handleAddArtist} 
            artist={editingArtist} 
          />
        </div>
      </main>
      <Footer />
    </>
  );
};

export default PunkRockPage;