import React, { useState, useRef, useEffect, useCallback } from 'react';
import { v4 as uuidv4 } from 'uuid';
import { Plus, Play, Pause, SkipForward, SkipBack, Volume2, Gauge, Layout } from 'lucide-react';
import { Article, PlaybackStatus, PlayerState, VoiceName } from './types';
import { AVAILABLE_VOICES, MIN_SPEED, MAX_SPEED, SPEED_STEP } from './constants';
import { extractArticleContent, generateSpeechFromText } from './services/geminiService';
import { base64ToUint8Array, createWavBlob } from './services/audioUtils';
import { QueueItem } from './components/QueueItem';
import { VoiceSelector } from './components/VoiceSelector';
import { ReaderView } from './components/ReaderView';

export default function App() {
  // -- State --
  const [inputUrl, setInputUrl] = useState('');
  const [queue, setQueue] = useState<Article[]>([]);
  // Selected article for reading (defaults to playing article)
  const [viewId, setViewId] = useState<string | null>(null);
  
  const [playerState, setPlayerState] = useState<PlayerState>({
    isPlaying: false,
    playbackRate: 1.0,
    currentArticleId: null,
    selectedVoice: VoiceName.Puck,
  });

  // -- Refs --
  const audioRef = useRef<HTMLAudioElement>(new Audio());
  const audioSrcRef = useRef<string | null>(null);

  // -- Helpers --
  const getCurrentArticle = () => queue.find(a => a.id === playerState.currentArticleId);
  const getViewingArticle = () => {
    // If user manually selected an article to view, show that. 
    // Otherwise show the currently playing one.
    // Otherwise show the first one.
    if (viewId) return queue.find(a => a.id === viewId);
    if (playerState.currentArticleId) return queue.find(a => a.id === playerState.currentArticleId);
    if (queue.length > 0) return queue[0];
    return null;
  };
  
  const updateArticleStatus = (id: string, status: PlaybackStatus, errorMessage?: string, audioUrl?: string, title?: string, text?: string) => {
    setQueue(prev => prev.map(item => {
      if (item.id !== id) return item;
      return {
        ...item,
        status,
        errorMessage,
        audioUrl: audioUrl || item.audioUrl,
        title: title || item.title,
        text: text || item.text
      };
    }));
  };

  // -- Handlers --

  // 1. Add URL to Queue
  const handleAddUrl = async () => {
    if (!inputUrl.trim()) return;
    const id = uuidv4();
    const newArticle: Article = {
      id,
      url: inputUrl,
      title: 'Fetching info...',
      text: '',
      status: PlaybackStatus.LOADING_TEXT
    };
    
    setQueue(prev => [...prev, newArticle]);
    setInputUrl('');
    // Auto view the new article while loading
    if (!playerState.isPlaying) {
        setViewId(id);
    }

    // Start fetching text immediately
    try {
      const { title, text } = await extractArticleContent(newArticle.url);
      updateArticleStatus(id, PlaybackStatus.IDLE, undefined, undefined, title, text);
    } catch (error: any) {
      updateArticleStatus(id, PlaybackStatus.ERROR, error.message || "Failed to load article");
    }
  };

  // 2. Generate Audio for an article
  const prepareAudio = async (articleId: string): Promise<string | null> => {
    const article = queue.find(a => a.id === articleId);
    if (!article) return null;
    
    // If already has audio return it
    if (article.audioUrl) return article.audioUrl;

    updateArticleStatus(articleId, PlaybackStatus.LOADING_AUDIO);

    try {
      if (!article.text || article.text.length < 10) {
          throw new Error("No text available to read.");
      }
      const base64Audio = await generateSpeechFromText(article.text, playerState.selectedVoice);
      const pcmData = base64ToUint8Array(base64Audio);
      const wavBlob = createWavBlob(pcmData);
      const audioUrl = URL.createObjectURL(wavBlob);
      
      updateArticleStatus(articleId, PlaybackStatus.READY, undefined, audioUrl);
      return audioUrl;
    } catch (error: any) {
      updateArticleStatus(articleId, PlaybackStatus.ERROR, error.message || "Failed to generate speech");
      return null;
    }
  };

  // 3. Play Logic
  const playArticle = useCallback(async (id: string) => {
    const article = queue.find(a => a.id === id);
    if (!article) return;

    // If currently playing a different one, pause it.
    if (playerState.currentArticleId && playerState.currentArticleId !== id) {
      audioRef.current.pause();
    }

    setPlayerState(prev => ({ ...prev, currentArticleId: id, isPlaying: true }));
    // Also switch view to the playing article
    setViewId(id);
    
    let src = article.audioUrl;
    
    // Check if we need to generate audio
    if (!src) {
      src = await prepareAudio(id);
    }

    if (src) {
      // Only update src if it's different to avoid reload
      if (audioSrcRef.current !== src) {
        audioRef.current.src = src;
        audioSrcRef.current = src;
        // Apply current speed
        audioRef.current.playbackRate = playerState.playbackRate;
      }
      
      try {
        await audioRef.current.play();
        updateArticleStatus(id, PlaybackStatus.PLAYING);
      } catch (e) {
        console.error("Play error", e);
        setPlayerState(prev => ({ ...prev, isPlaying: false }));
      }
    }
  }, [queue, playerState.currentArticleId, playerState.playbackRate, playerState.selectedVoice]);

  const pausePlayback = useCallback(() => {
    audioRef.current.pause();
    setPlayerState(prev => ({ ...prev, isPlaying: false }));
    if (playerState.currentArticleId) {
      updateArticleStatus(playerState.currentArticleId, PlaybackStatus.PAUSED);
    }
  }, [playerState.currentArticleId]);

  const handleSpeedChange = (newSpeed: number) => {
    // Clamp
    const speed = Math.max(MIN_SPEED, Math.min(MAX_SPEED, newSpeed));
    setPlayerState(prev => ({ ...prev, playbackRate: speed }));
    if (audioRef.current) {
      audioRef.current.playbackRate = speed;
    }
  };

  // Auto-Advance Logic
  useEffect(() => {
    const audio = audioRef.current;
    
    const handleEnded = () => {
      const currentId = playerState.currentArticleId;
      if (currentId) {
        updateArticleStatus(currentId, PlaybackStatus.COMPLETED);
        
        // Find next
        const currentIndex = queue.findIndex(a => a.id === currentId);
        if (currentIndex !== -1 && currentIndex < queue.length - 1) {
          const nextId = queue[currentIndex + 1].id;
          playArticle(nextId);
        } else {
          setPlayerState(prev => ({ ...prev, isPlaying: false }));
        }
      }
    };

    audio.addEventListener('ended', handleEnded);
    return () => {
      audio.removeEventListener('ended', handleEnded);
    };
  }, [playerState.currentArticleId, queue, playArticle]);


  // -- Render --
  
  const currentArticle = getCurrentArticle();
  const viewingArticle = getViewingArticle();

  return (
    <div className="min-h-screen flex flex-col bg-slate-50 pb-32">
      {/* Header */}
      <header className="bg-white border-b border-slate-200 px-6 py-4 sticky top-0 z-20 shadow-sm">
        <div className="max-w-7xl mx-auto flex items-center justify-between">
          <div className="flex items-center gap-2">
            <div className="bg-blue-600 text-white p-2 rounded-lg">
              <Volume2 className="w-6 h-6" />
            </div>
            <h1 className="text-xl font-bold text-slate-900 tracking-tight hidden sm:block">NewsCaster AI</h1>
          </div>
          
          <VoiceSelector 
            selectedVoice={playerState.selectedVoice}
            onVoiceChange={(v) => setPlayerState(prev => ({ ...prev, selectedVoice: v }))}
            disabled={playerState.isPlaying} 
          />
        </div>
      </header>

      {/* Main Content - Split Layout */}
      <main className="flex-grow px-4 py-6 max-w-7xl mx-auto w-full grid grid-cols-1 lg:grid-cols-12 gap-8">
        
        {/* Left Column: Controls & Queue (5 cols) */}
        <div className="lg:col-span-5 space-y-6">
            {/* Input Section */}
            <div className="bg-white p-1 rounded-2xl shadow-sm border border-slate-200 flex gap-2 items-center pl-4">
            <input 
                type="url" 
                placeholder="Paste article URL here..."
                className="flex-grow py-3 outline-none text-slate-700 bg-transparent placeholder:text-slate-400 min-w-0"
                value={inputUrl}
                onChange={(e) => setInputUrl(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && handleAddUrl()}
            />
            <button 
                onClick={handleAddUrl}
                disabled={!inputUrl.trim()}
                className="bg-slate-900 hover:bg-slate-800 disabled:bg-slate-300 text-white px-4 sm:px-6 py-3 rounded-xl font-medium transition-all flex items-center gap-2 flex-shrink-0"
            >
                <Plus className="w-4 h-4" />
                <span className="hidden sm:inline">Queue</span>
            </button>
            </div>

            {/* Queue List */}
            <div className="space-y-4">
            <div className="flex items-center justify-between px-1">
                <h2 className="text-sm font-semibold text-slate-500 uppercase tracking-wider">Up Next</h2>
                <span className="text-xs bg-slate-100 text-slate-600 px-2 py-1 rounded-full">{queue.length} articles</span>
            </div>
            
            <div className="space-y-3">
                {queue.length === 0 ? (
                <div className="text-center py-12 border-2 border-dashed border-slate-200 rounded-2xl text-slate-400 bg-white">
                    <p>No articles queued.</p>
                </div>
                ) : (
                queue.map(article => (
                    <div key={article.id} onClick={() => setViewId(article.id)} className="cursor-pointer">
                        <QueueItem 
                            article={article}
                            isActive={article.id === playerState.currentArticleId}
                            isPlaying={playerState.isPlaying}
                            onPlay={() => playArticle(article.id)}
                            onPause={pausePlayback}
                            onRemove={() => {
                                if (playerState.currentArticleId === article.id) {
                                pausePlayback();
                                setPlayerState(prev => ({ ...prev, currentArticleId: null }));
                                }
                                setQueue(prev => prev.filter(a => a.id !== article.id));
                                if (viewId === article.id) setViewId(null);
                            }}
                        />
                    </div>
                ))
                )}
            </div>
            </div>
        </div>

        {/* Right Column: Reader View (7 cols) */}
        <div className="lg:col-span-7 h-full hidden lg:block">
            <ReaderView article={viewingArticle} />
        </div>
        
        {/* Mobile: Reader View appears below if selected */}
        <div className="lg:hidden block">
             {viewingArticle && (
                 <div className="mt-8">
                     <h3 className="text-sm font-semibold text-slate-500 uppercase tracking-wider mb-2">Article Reader</h3>
                     <div className="h-[500px]">
                        <ReaderView article={viewingArticle} />
                     </div>
                 </div>
             )}
        </div>
      </main>

      {/* Sticky Player */}
      <div className="fixed bottom-0 left-0 right-0 bg-white/90 backdrop-blur-lg border-t border-slate-200 p-4 pb-6 shadow-[0_-4px_20px_rgba(0,0,0,0.05)] z-30">
        <div className="max-w-7xl mx-auto flex flex-col sm:flex-row items-center gap-4 sm:gap-8">
          
          {/* Current Track Info */}
          <div className="flex-grow w-full sm:w-auto min-w-0 text-center sm:text-left">
            {currentArticle ? (
              <div>
                <h4 className="font-bold text-slate-900 truncate">{currentArticle.title}</h4>
                <p className="text-xs text-slate-500 truncate">Playing from queue</p>
              </div>
            ) : (
              <div className="text-slate-400 text-sm font-medium">Ready to play</div>
            )}
          </div>

          {/* Controls */}
          <div className="flex items-center gap-6">
            
            {/* Speed Control */}
            <div className="hidden sm:flex items-center gap-2 group relative">
               <Gauge className="w-4 h-4 text-slate-400" />
               <div className="flex items-center gap-2 bg-slate-100 rounded-lg p-1">
                 <button 
                    className="w-6 h-6 flex items-center justify-center hover:bg-white rounded text-xs font-bold text-slate-600 transition-colors"
                    onClick={() => handleSpeedChange(playerState.playbackRate - SPEED_STEP)}
                 >-</button>
                 <span className="text-xs font-mono w-8 text-center font-bold text-blue-600">{playerState.playbackRate.toFixed(1)}x</span>
                 <button 
                    className="w-6 h-6 flex items-center justify-center hover:bg-white rounded text-xs font-bold text-slate-600 transition-colors"
                    onClick={() => handleSpeedChange(playerState.playbackRate + SPEED_STEP)}
                 >+</button>
               </div>
            </div>

            {/* Main Transport */}
            <div className="flex items-center gap-4">
              <button 
                className="p-2 text-slate-400 hover:text-slate-600 transition-colors"
                onClick={() => {
                   const idx = queue.findIndex(a => a.id === playerState.currentArticleId);
                   if (idx > 0) playArticle(queue[idx - 1].id);
                }}
                disabled={!playerState.currentArticleId || queue.findIndex(a => a.id === playerState.currentArticleId) <= 0}
              >
                <SkipBack className="w-5 h-5" />
              </button>

              <button 
                className="w-12 h-12 rounded-full bg-slate-900 hover:bg-slate-800 text-white flex items-center justify-center shadow-lg hover:shadow-xl hover:scale-105 transition-all active:scale-95"
                onClick={() => {
                  if (playerState.isPlaying) pausePlayback();
                  else if (playerState.currentArticleId) playArticle(playerState.currentArticleId);
                  else if (queue.length > 0) playArticle(queue[0].id);
                }}
                disabled={queue.length === 0}
              >
                {playerState.isPlaying ? <Pause className="w-5 h-5 fill-current" /> : <Play className="w-5 h-5 fill-current ml-1" />}
              </button>

              <button 
                className="p-2 text-slate-400 hover:text-slate-600 transition-colors"
                onClick={() => {
                   const idx = queue.findIndex(a => a.id === playerState.currentArticleId);
                   if (idx !== -1 && idx < queue.length - 1) playArticle(queue[idx + 1].id);
                }}
                disabled={!playerState.currentArticleId || queue.findIndex(a => a.id === playerState.currentArticleId) >= queue.length - 1}
              >
                <SkipForward className="w-5 h-5" />
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
