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

const Home: React.FC = () => {
  const { artists, epochs, countries, loading, error, addArtist, editArtist, removeArtist, toggleSortOrder, sortOrder } = useArtists();
  const [editingArtist, setEditingArtist] = React.useState<Artist | null>(null);

  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 handleSubmit = async (artist: Artist) => {
    if (editingArtist && editingArtist.id) {
      await editArtist(editingArtist.id, artist);
    } else {
      await addArtist(artist);
    }
  };

  return (
    <div className="container py-4">
      <div className="d-flex justify-content-between align-items-center mb-3">
        <h1 className="text-punk mb-0">Главная</h1>
        <button 
          className="btn btn-punk"
          onClick={toggleSortOrder}
        >
          <i className={`bi bi-sort-alpha-${sortOrder === 'asc' ? 'down' : 'up'}`}></i>
          {sortOrder === 'asc' ? 'Я → А' : 'А → Я'}
        </button>
      </div>
      <ArtistForm
        countries={countries}
        epochs={epochs}
        onSubmit={handleSubmit}
        artist={editingArtist}
        onCancel={() => setEditingArtist(null)}
      />
      <ArtistList 
        artists={artists} 
        epochs={epochs} 
        countries={countries} 
        onEdit={setEditingArtist} 
        onDelete={removeArtist} 
      />
    </div>
  );
};

export default Home;