import React, { useState, useEffect } from 'react'
import Navbar from './components/Navbar'
import Player from './components/Player'
import HomePage from './pages/HomePage'
import PlaylistsPage from './pages/PlaylistsPage'
import PlaylistDetailPage from './pages/PlaylistDetailPage'
import SongDetailPage from './pages/SongDetailPage'
import LoginPage from './pages/LoginPage'
import RegisterPage from './pages/RegisterPage'
import { AuthContext } from './context/AuthContext'
import { API_BASE_URL } from './services/api'

function App() {
  const [currentUser, setCurrentUser] = useState(null)
  const [isAuthenticated, setIsAuthenticated] = useState(false)
  const [currentSong, setCurrentSong] = useState(null)
  const [isPlaying, setIsPlaying] = useState(false)
  const [currentPath, setCurrentPath] = useState(window.location.pathname)

  // 检查用户认证状态
  useEffect(() => {
    const token = localStorage.getItem('token')
    if (token) {
      // 验证token有效性
      fetch(`${API_BASE_URL}/api/auth/me`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      .then(res => {
        if (res.ok) {
          return res.json()
        }
        throw new Error('Invalid token')
      })
      .then(user => {
        setCurrentUser(user)
        setIsAuthenticated(true)
      })
      .catch(err => {
        localStorage.removeItem('token')
      })
    }
  }, [])
  
  // 监听URL变化，确保组件重新渲染
  useEffect(() => {
    const handleLocationChange = () => {
      setCurrentPath(window.location.pathname)
    }
    
    window.addEventListener('popstate', handleLocationChange)
    window.addEventListener('pushstate', handleLocationChange)
    window.addEventListener('replacestate', handleLocationChange)
    
    // 自定义事件，用于监听history.pushState和history.replaceState的调用
    const originalPushState = history.pushState
    history.pushState = function(...args) {
      const result = originalPushState.apply(this, args)
      window.dispatchEvent(new Event('pushstate'))
      return result
    }
    
    const originalReplaceState = history.replaceState
    history.replaceState = function(...args) {
      const result = originalReplaceState.apply(this, args)
      window.dispatchEvent(new Event('replacestate'))
      return result
    }
    
    return () => {
      window.removeEventListener('popstate', handleLocationChange)
      window.removeEventListener('pushstate', handleLocationChange)
      window.removeEventListener('replacestate', handleLocationChange)
    }
  }, [])

  // 登录处理
  const handleLogin = (user, token) => {
    setCurrentUser(user)
    setIsAuthenticated(true)
    localStorage.setItem('token', token)
  }

  // 登出处理
  const handleLogout = () => {
    setCurrentUser(null)
    setIsAuthenticated(false)
    localStorage.removeItem('token')
  }

  // 播放歌曲
  const playSong = (song) => {
    setCurrentSong(song)
    setIsPlaying(true)
  }

  // 暂停/继续播放
  const togglePlay = () => {
    setIsPlaying(!isPlaying)
  }



  // 简单的路由逻辑
  const getCurrentPage = () => {
    const path = currentPath
    
    if (path === '/login') {
      return <LoginPage onLogin={handleLogin} />
    }
    
    if (path === '/register') {
      return <RegisterPage />
    }
    
    if (path.startsWith('/playlists/')) {
      const playlistId = path.split('/')[2]
      return <PlaylistDetailPage playlistId={playlistId} onPlaySong={playSong} />
    }
    
    if (path.startsWith('/songs/')) {
      const songId = path.split('/')[2]
      return <SongDetailPage songId={songId} />
    }
    
    if (path === '/playlists') {
      return <PlaylistsPage onPlaySong={playSong} />
    }
    
    return <HomePage onPlaySong={playSong} />
  }

  return (
    <AuthContext.Provider value={{ currentUser, isAuthenticated, onLogin: handleLogin, onLogout: handleLogout }}>
      <div className="app-container">
        <Navbar />
        
        <main className="main-content">
          {getCurrentPage()}
        </main>
        
        {currentSong && (
          <Player 
            song={currentSong} 
            isPlaying={isPlaying} 
            onTogglePlay={togglePlay} 
          />
        )}
        

      </div>
    </AuthContext.Provider>
  )
}

export default App