import { useState } from 'react';

export const useAudioPlayer = () => {
  const [playedSongs, setPlayedSongs] = useState({});
  const [currentlyPlaying, setCurrentlyPlaying] = useState(null);
  const [pageDurations, setPageDurations] = useState({});
  const [audioDurations, setAudioDurations] = useState({});

  const handlePlay = (index) => {
    setCurrentlyPlaying(index);
    setPlayedSongs(prev => ({ ...prev, [index]: true }));
  };

  const handleNext = (currentPageAudioFiles) => {
    if (currentPageAudioFiles && currentPageAudioFiles.length > 0 && (currentlyPlaying === null || currentlyPlaying < currentPageAudioFiles.length - 1)) {
      const nextIndex = currentlyPlaying === null ? 0 : currentlyPlaying + 1;
      setCurrentlyPlaying(nextIndex);
      setPlayedSongs(prev => ({ ...prev, [nextIndex]: true }));
    } else {
      setCurrentlyPlaying(null);
    }
  };

  const handlePrev = () => {
    if (currentlyPlaying !== null && currentlyPlaying > 0) {
      const prevIndex = currentlyPlaying - 1;
      setCurrentlyPlaying(prevIndex);
      setPlayedSongs(prev => ({ ...prev, [prevIndex]: true }));
    }
  };

  const handleEnded = (currentPageAudioFiles) => {
    handleNext(currentPageAudioFiles);
  };

  const handleLoadedMetadata = (pageIndex, audioIndex, duration) => {
    setAudioDurations(prev => ({
      ...prev,
      [`${pageIndex}-${audioIndex}`]: duration
    }));
  };

  const setIsPlaying = (playing, index) => {
    if (playing) {
      setCurrentlyPlaying(index);
    } else if (currentlyPlaying === index) {
      setCurrentlyPlaying(null);
    }
  };

  return {
    playedSongs,
    currentlyPlaying,
    pageDurations,
    audioDurations,
    setPageDurations,
    handlePlay,
    handleNext,
    handlePrev,
    handleEnded,
    handleLoadedMetadata,
    setIsPlaying
  };
};