import { useState, useEffect, useCallback, useRef } from 'react';

export function useTTS() {
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentSegmentIndex, setCurrentSegmentIndex] = useState(-1);
  const [isPaused, setIsPaused] = useState(false);
  const [audioElements, setAudioElements] = useState([]);
  const [progress, setProgress] = useState(0);
  const audioRef = useRef(null);
  const segmentsRef = useRef([]);

  // Initialize audio from base64 segments
  const initializeAudio = useCallback((segments) => {
    if (!segments || segments.length === 0) {
      console.log('[TTS] No segments to initialize');
      return;
    }

    console.log('[TTS] Initializing audio with', segments.length, 'segments');

    // Create audio elements for each segment
    const audioEls = segments.map((seg, idx) => {
      if (!seg.audioBase64) return null;

      const audio = new Audio();
      audio.src = `data:${seg.contentType || 'audio/mpeg'};base64,${seg.audioBase64}`;
      audio.dataset.index = idx;
      audio.dataset.type = seg.type;
      audio.dataset.speaker = seg.speaker || '';

      // Handle segment end
      audio.addEventListener('ended', () => {
        console.log('[TTS] Segment', idx, 'ended');
        handleSegmentEnd(idx);
      });

      // Handle errors
      audio.addEventListener('error', (e) => {
        console.error('[TTS] Audio error on segment', idx, e);
        handleSegmentEnd(idx);
      });

      return audio;
    }).filter(Boolean);

    segmentsRef.current = segments;
    setAudioElements(audioEls);
    console.log('[TTS] Audio initialized:', audioEls.length, 'elements');
  }, []);

  const handleSegmentEnd = useCallback((currentIndex) => {
    const nextIndex = currentIndex + 1;
    
    if (nextIndex < segmentsRef.current.length && !isPaused) {
      setCurrentSegmentIndex(nextIndex);
      playSegment(nextIndex);
    } else {
      setIsPlaying(false);
      setCurrentSegmentIndex(-1);
      setProgress(100);
    }
  }, [isPaused]);

  const playSegment = useCallback((index) => {
    const audio = audioElements[index];
    if (!audio) {
      console.warn('[TTS] No audio element at index', index);
      return;
    }

    console.log('[TTS] Playing segment', index);
    audio.currentTime = 0;
    audio.play().catch(err => {
      console.error('[TTS] Play error:', err);
      setIsPlaying(false);
    });
  }, [audioElements]);

  const play = useCallback(() => {
    if (audioElements.length === 0) {
      console.warn('[TTS] No audio to play');
      return;
    }

    console.log('[TTS] Play called, paused:', isPaused);
    
    if (isPaused && currentSegmentIndex >= 0) {
      // Resume from current position
      const audio = audioElements[currentSegmentIndex];
      audio.play().catch(err => {
        console.error('[TTS] Resume error:', err);
      });
      setIsPaused(false);
      setIsPlaying(true);
    } else {
      // Start from beginning
      setCurrentSegmentIndex(0);
      playSegment(0);
      setIsPlaying(true);
      setIsPaused(false);
    }
  }, [audioElements, isPaused, currentSegmentIndex, playSegment]);

  const pause = useCallback(() => {
    if (currentSegmentIndex >= 0 && audioElements[currentSegmentIndex]) {
      audioElements[currentSegmentIndex].pause();
      setIsPaused(true);
      console.log('[TTS] Paused at segment', currentSegmentIndex);
    }
  }, [currentSegmentIndex, audioElements]);

  const stop = useCallback(() => {
    audioElements.forEach(audio => {
      audio.pause();
      audio.currentTime = 0;
    });
    setIsPlaying(false);
    setIsPaused(false);
    setCurrentSegmentIndex(-1);
    setProgress(0);
    console.log('[TTS] Stopped');
  }, [audioElements]);

  const skipToSegment = useCallback((index) => {
    if (index < 0 || index >= audioElements.length) return;
    
    stop();
    setCurrentSegmentIndex(index);
    playSegment(index);
    setIsPlaying(true);
  }, [audioElements, stop, playSegment]);

  // Update progress as audio plays
  useEffect(() => {
    if (!isPlaying || isPaused || currentSegmentIndex < 0) return;

    const updateProgress = () => {
      const audio = audioElements[currentSegmentIndex];
      if (!audio) return;

      const segmentProgress = (audio.currentTime / audio.duration) * 100;
      const totalProgress = ((currentSegmentIndex + segmentProgress / 100) / segmentsRef.current.length) * 100;
      setProgress(totalProgress);
    };

    const interval = setInterval(updateProgress, 100);
    return () => clearInterval(interval);
  }, [isPlaying, isPaused, currentSegmentIndex, audioElements]);

  // Cleanup on unmount
  useEffect(() => {
    return () => {
      audioElements.forEach(audio => {
        audio.pause();
        audio.src = '';
      });
    };
  }, [audioElements]);

  return {
    isPlaying,
    isPaused,
    currentSegmentIndex,
    progress,
    totalSegments: audioElements.length,
    initializeAudio,
    play,
    pause,
    stop,
    skipToSegment
  };
}

export default useTTS;
