import { useState, useEffect } from 'react';
import { getArtists, createArtist, updateArtist, deleteArtist, getEpochs, getCountries } from '../services/api';
import { Artist, Epoch, Country } from '../types';
import { v4 as uuidv4 } from 'uuid';
const useArtists = () => {
  const [artists, setArtists] = useState<Artist[]>([]);
  const [epochs, setEpochs] = useState<Epoch[]>([]);
  const [countries, setCountries] = useState<Country[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc');

  const fetchData = async () => {
    try {
      setLoading(true);
      const [artistsData, epochsData, countriesData] = await Promise.all([
        getArtists(),
        getEpochs(),
        getCountries(),
      ]);
      console.log('Artists data:', artistsData.data);
      console.log('Epochs data:', epochsData.data);
      console.log('Countries data:', countriesData.data);

      const enrichedArtists = artistsData.data.map((artist: Artist) => ({
        ...artist,
        epoch: epochsData.data.find((e: Epoch) => e.id.toString() === artist.epochId.toString()),
        country: countriesData.data.find((c: Country) => c.id.toString() === artist.countryId.toString()),
      }));

      const sortedArtists = [...enrichedArtists].sort((a, b) =>
        sortOrder === 'asc'
          ? a.name.localeCompare(b.name)
          : b.name.localeCompare(a.name)
      );

      setArtists(sortedArtists);
      setEpochs(epochsData.data);
      setCountries(countriesData.data);
      setLoading(false);
    } catch (err: any) {
      setError(err.message);
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, [sortOrder]);

 

const addArtist = async (artist: Omit<Artist, 'id'>) => {
  const nameExists = artists.some(a => a.name.toLowerCase() === artist.name.toLowerCase());
  if (nameExists) {
    throw new Error('Исполнитель с таким именем уже существует!');
  }

  // Генерируем уникальный id на клиентской стороне
  const uniqueId = uuidv4();

  // Создаем новый объект артиста с id
  const artistWithId: Artist = {
    ...artist,
    id: uniqueId,
    epochId: artist.epochId.toString(),
    countryId: artist.countryId.toString(),
  };

  // Отправляем объект на сервер
  const response = await createArtist(artistWithId);

  const newArtist = {
    ...response.data,
    epoch: epochs.find(e => e.id.toString() === response.data.epochId.toString()),
    country: countries.find(c => c.id.toString() === response.data.countryId.toString()),
  };

  const updatedArtists = [...artists, newArtist].sort((a, b) =>
    sortOrder === 'asc'
      ? a.name.localeCompare(b.name)
      : b.name.localeCompare(a.name)
  );

  setArtists(updatedArtists);
};

  const editArtist = async (id: string, artistData: Partial<Artist>) => {
  if (artistData.name !== undefined) {
    const nameExists = artists.some(a => a.id !== id && a.name.toLowerCase() === artistData.name!.toLowerCase());
    if (nameExists) {
      throw new Error('Исполнитель с таким именем уже существует!');
    }
  }

  try {
    const response = await updateArtist(id, artistData);
    const updatedArtist = {
      ...response.data,
      epoch: epochs.find(e => e.id.toString() === response.data.epochId.toString()),
      country: countries.find(c => c.id.toString() === response.data.countryId.toString()),
    };
    const updatedArtists = artists.map(a => a.id === id ? updatedArtist : a);
    setArtists(updatedArtists.sort(((a, b) => 
      sortOrder === 'asc' ? a.name.localeCompare(b.name) : b.name.localeCompare(a.name)
    )));
  } catch (err: any) {
    setError(`Ошибка при изменении: ${err.message}. Сервер ответил ${err.response?.status}`);
    console.error('Edit error:', err);
  }
};

  const removeArtist = async (id: string) => {
    console.log(`Attempting to delete artist with id: ${id}`);
    console.log('Current artists:', artists);
    const artistExists = artists.find(a => a.id.toString() === id.toString());
    if (!artistExists) {
      setError(`Ошибка: Исполнитель с id ${id} не найден в текущем списке!`);
      return;
    }
    try {
      await deleteArtist(id);
      // Повторно загружаем данные с сервера после удаления
      await fetchData();
    } catch (err: any) {
      setError(`Ошибка при удалении: ${err.message}. Сервер ответил ${err.response?.status}`);
      console.error('Delete error:', err);
    }
  };

  const toggleSortOrder = () => {
    setSortOrder(prev => (prev === 'asc' ? 'desc' : 'asc'));
  };

  return { artists, epochs, countries, loading, error, addArtist, editArtist, removeArtist, toggleSortOrder, sortOrder };
};

export default useArtists;