import React, { useState, useEffect, useRef } from 'react'

function SongDetailPage({ songId }) {
  // 模拟林俊杰歌曲数据
  const songData = {
    1: {
      id: 1,
      title: '江南',
      artist: '林俊杰',
      album: '第二天堂',
      coverUrl: 'https://picsum.photos/seed/jj1/800/800',
      lyrics: [
        '风到这里就是粘',
        '粘住过客的思念',
        '雨到了这里缠成线',
        '缠着我们留恋人世间',
        '你在身边就是缘',
        '缘分写在三生石上面',
        '爱有万分之一甜',
        '宁愿我就葬在这一点'
      ],
      audioUrl: 'http://downsc.chinaz.net/Files/DownLoad/sound1/201906/11582.mp3'
    },
    2: {
      id: 2,
      title: '小酒窝',
      artist: '林俊杰',
      album: 'JJ陆',
      coverUrl: 'https://picsum.photos/seed/jj2/800/800',
      lyrics: [
        '我还在寻找',
        '一个依靠和一个拥抱',
        '谁替我祈祷',
        '替我烦恼',
        '为我生气为我闹',
        '幸福开始有预兆',
        '缘分让我们慢慢紧靠'
      ],
      audioUrl: 'http://downsc.chinaz.net/files/download/sound1/201206/1638.mp3'
    },
    3: {
      id: 3,
      title: '曹操',
      artist: '林俊杰',
      album: '曹操',
      coverUrl: 'https://picsum.photos/seed/jj3/800/800',
      lyrics: [
        '不是英雄 不读三国',
        '若是英雄 怎么能不懂寂寞',
        '独自走下长坂坡 月光太温柔',
        '曹操不啰嗦 一心要那荆州',
        '用阴谋 阳谋 明说 暗夺的摸'
      ],
      audioUrl: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-4.mp3'
    },
    4: {
      id: 4,
      title: '她说',
      artist: '林俊杰',
      album: '她说',
      coverUrl: 'https://picsum.photos/seed/jj4/800/800',
      lyrics: [
        '她说 林俊杰',
        '她静悄悄的来过',
        '她慢慢带走沉默',
        '只是最后的承诺',
        '还是没有带走了寂寞',
        '我们爱的没有错',
        '只是美丽的独秀太折磨'
      ],
      audioUrl: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3'
    },
    5: {
      id: 5,
      title: '背对背拥抱',
      artist: '林俊杰',
      album: '100天',
      coverUrl: 'https://picsum.photos/seed/jj5/800/800',
      lyrics: [
        '话总说不清楚 该怎么明了',
        '一字一句像圈套',
        '旧帐总翻不完 谁无理取闹',
        '你的双手甩开刚好的微妙',
        '然后战火再燃烧',
        '我们背对背拥抱 滥用沉默在咆哮'
      ],
      audioUrl: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3'
    },
    6: {
      id: 6,
      title: '一千年以后',
      artist: '林俊杰',
      album: '编号89757',
      coverUrl: 'https://picsum.photos/seed/jj6/800/800',
      lyrics: [
        '心跳乱了节奏',
        '梦也不自由',
        '爱是个绝对承诺 不说',
        '撑到一千年以后',
        '放任无奈 淹没尘埃',
        '我在废墟之中守着你走来'
      ],
      audioUrl: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3'
    }
  }
  
  // 根据歌曲ID获取对应的歌曲数据
  const mockSong = songData[songId] || songData[1]

  const [song, setSong] = useState(mockSong)
  const [isPlaying, setIsPlaying] = useState(true)
  const [currentLyric, setCurrentLyric] = useState(0)

  // 当songId变化时，更新歌曲数据
  useEffect(() => {
    const newSong = songData[songId] || songData[1]
    setSong(newSong)
    // 重置当前歌词索引
    setCurrentLyric(0)
    // 设置为播放状态
    setIsPlaying(true)
  }, [songId])
  const audioRef = useRef(null)
  const hasInteracted = useRef(false)

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

  // 上一首歌曲
  const playPreviousSong = () => {
    // 获取所有歌曲ID并按数字顺序排序
    const songIds = Object.keys(songData).map(id => parseInt(id)).sort((a, b) => a - b)
    const currentIndex = songIds.indexOf(song.id)
    
    // 只有当前不是第一首歌曲时，才允许跳转到上一首
    if (currentIndex > 0) {
      const previousIndex = currentIndex - 1
      const previousSongId = songIds[previousIndex]
      
      // 更新URL和状态，使用/songs/格式
      window.history.pushState(null, '', `/songs/${previousSongId}`)
      window.dispatchEvent(new Event('pushstate'))
    }
  }

  // 下一首歌曲
  const playNextSong = () => {
    // 获取所有歌曲ID并按数字顺序排序
    const songIds = Object.keys(songData).map(id => parseInt(id)).sort((a, b) => a - b)
    const currentIndex = songIds.indexOf(song.id)
    
    // 只有当前不是最后一首歌曲时，才允许跳转到下一首
    if (currentIndex < songIds.length - 1) {
      const nextIndex = currentIndex + 1
      const nextSongId = songIds[nextIndex]
      
      // 更新URL和状态，使用/songs/格式
      window.history.pushState(null, '', `/songs/${nextSongId}`)
      window.dispatchEvent(new Event('pushstate'))
    }
  }

  // 当播放状态变化时，控制音频播放
  useEffect(() => {
    if (audioRef.current) {
      if (isPlaying) {
        audioRef.current.play().catch(err => {
          console.error('播放失败:', err)
          setIsPlaying(false)
        })
      } else {
        audioRef.current.pause()
      }
    }
  }, [isPlaying])

  // 当歌曲URL变化时，重新加载音频
  useEffect(() => {
    if (audioRef.current) {
      // 重置音频元素并重新加载
      audioRef.current.load()
      // 如果当前是播放状态，则自动开始播放新音频
      if (isPlaying) {
        audioRef.current.play().catch(err => {
          console.error('自动播放失败:', err)
          // 自动播放失败时，不立即设置为暂停状态，保持播放意图
        })
      }
    }
  }, [song.audioUrl, isPlaying])

  // 尝试自动播放音乐，并添加用户交互事件监听器
  useEffect(() => {
    const attemptPlay = () => {
      if (audioRef.current && isPlaying && !hasInteracted.current) {
        audioRef.current.play().then(() => {
          hasInteracted.current = true
        }).catch(err => {
          console.log('自动播放被浏览器阻止，等待用户交互...')
        })
      }
    }

    // 组件加载时尝试自动播放
    attemptPlay()

    // 添加点击事件监听器，当用户与页面交互时尝试播放
    const handleInteraction = () => {
      if (!hasInteracted.current) {
        attemptPlay()
      }
    }

    document.addEventListener('click', handleInteraction)
    document.addEventListener('touchstart', handleInteraction)
    document.addEventListener('keydown', handleInteraction)

    // 清理事件监听器
    return () => {
      document.removeEventListener('click', handleInteraction)
      document.removeEventListener('touchstart', handleInteraction)
      document.removeEventListener('keydown', handleInteraction)
    }
  }, [isPlaying])

  // 模拟歌词滚动
  useEffect(() => {
    let interval
    if (isPlaying) {
      interval = setInterval(() => {
        setCurrentLyric(prev => (prev + 1) % song.lyrics.length)
      }, 3000)
    }
    return () => clearInterval(interval)
  }, [isPlaying, song.lyrics.length])

  return (
    <div className="song-detail-page">
      <div className="song-detail-header">
        <button 
          className="back-btn"
          onClick={() => {
            window.history.pushState(null, '', '/');
            // 触发自定义事件以确保App组件重新渲染
            window.dispatchEvent(new Event('pushstate'));
          }}
        >
          ←
        </button>
      </div>

      <div className="song-detail-content">
        <div className="album-cover-container">
          <div className="album-cover">
            <img 
              src={song.coverUrl} 
              alt={`${song.title} - ${song.artist}`} 
            />
          </div>
        </div>

        <div className="song-info">
          <h1 className="song-title">{song.title}</h1>
          <p className="song-artist">{song.artist}</p>
        </div>

        <div className="lyrics-container">
          <div className="lyrics-scroll">
            {song.lyrics.map((line, index) => (
              <p 
                key={index} 
                className={`lyric-line ${index === currentLyric ? 'active' : ''}`}
              >
                {line}
              </p>
            ))}
          </div>
        </div>

        <div className="playback-controls">
          <button className="control-btn" onClick={playPreviousSong}>⏮</button>
          <button 
            className="play-btn-large"
            onClick={togglePlay}
          >
            {isPlaying ? '⏸' : '▶'}
          </button>
          <button className="control-btn" onClick={playNextSong}>⏭</button>
        </div>

        <div className="player-actions">
          <button className="action-btn">❤️</button>
          <button className="action-btn">📋</button>
        </div>
      </div>

      {/* 音频播放器元素 */}
      <audio 
        ref={audioRef} 
        src={song.audioUrl} 
        preload="auto"
      />
    </div>
  )
}

export default SongDetailPage