import React, { useState, useEffect } from 'react'
import { useAuth } from '../context/AuthContext'
import { playlistAPI } from '../services/api'

function PlaylistsPage() {
  const { isAuthenticated } = useAuth()
  const [playlists, setPlaylists] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)
  const [searchKeyword, setSearchKeyword] = useState('')

  // 获取所有歌单
  const fetchPlaylists = async () => {
    try {
      setLoading(true)
      // 模拟API请求 - 使用本地模拟数据
      const mockPlaylists = [
        {
          id: 1,
          name: '我的最爱',
          songs: [
            { id: 1, title: '歌曲1', artist: '歌手1', duration: '3:45' },
            { id: 2, title: '歌曲2', artist: '歌手2', duration: '4:12' },
            { id: 3, title: '歌曲3', artist: '歌手3', duration: '3:58' }
          ]
        },
        {
          id: 2,
          name: '工作时听',
          songs: [
            { id: 4, title: '轻松音乐1', artist: '艺术家A', duration: '5:20' },
            { id: 5, title: '轻松音乐2', artist: '艺术家B', duration: '4:35' }
          ]
        },
        {
          id: 3,
          name: '运动节奏',
          songs: [
            { id: 6, title: '动感音乐1', artist: 'DJ X', duration: '3:15' },
            { id: 7, title: '动感音乐2', artist: 'DJ Y', duration: '2:58' },
            { id: 8, title: '动感音乐3', artist: 'DJ Z', duration: '3:42' }
          ]
        }
      ]
      
      // 模拟网络延迟
      await new Promise(resolve => setTimeout(resolve, 500))
      setPlaylists(mockPlaylists)
    } catch (err) {
      setError('无法加载歌单，请稍后再试')
      console.error('Error fetching playlists:', err)
    } finally {
      setLoading(false)
    }
  }

  // 搜索歌单
  const handleSearch = async () => {
    if (!searchKeyword.trim()) {
      fetchPlaylists()
      return
    }

    try {
      setLoading(true)
      // 模拟搜索功能 - 在本地模拟数据中过滤
      const filteredPlaylists = playlists.filter(playlist => 
        playlist.name.toLowerCase().includes(searchKeyword.toLowerCase())
      )
      
      // 模拟网络延迟
      await new Promise(resolve => setTimeout(resolve, 500))
      setPlaylists(filteredPlaylists)
    } catch (err) {
      setError('搜索失败，请稍后再试')
      console.error('Error searching playlists:', err)
    } finally {
      setLoading(false)
    }
  }

  // 删除歌单
  const handleDelete = async (id) => {
    if (window.confirm('确定要删除这个歌单吗？')) {
      try {
        await playlistAPI.delete(id)
        setPlaylists(prev => prev.filter(p => p.id !== id))
      } catch (err) {
        setError('删除失败，请稍后再试')
        console.error('Error deleting playlist:', err)
      }
    }
  }

  // 创建新歌单
  const handleCreatePlaylist = () => {
    const name = prompt('请输入新歌单名称：')
    if (name && name.trim()) {
      createPlaylist(name.trim())
    }
  }

  // 创建歌单API调用
  const createPlaylist = async (name) => {
    try {
      const newPlaylist = await playlistAPI.create({ name })
      setPlaylists(prev => [newPlaylist, ...prev])
    } catch (err) {
      setError('创建歌单失败，请稍后再试')
      console.error('Error creating playlist:', err)
    }
  }

  // 复制歌单
  const handleCopyPlaylist = async (id, currentName) => {
    const newName = prompt('请输入复制后的歌单名称：', `${currentName} - 副本`)
    if (newName && newName.trim()) {
      try {
        const copiedPlaylist = await playlistAPI.copy(id, newName.trim())
        setPlaylists(prev => [copiedPlaylist, ...prev])
      } catch (err) {
        setError('复制歌单失败，请稍后再试')
        console.error('Error copying playlist:', err)
      }
    }
  }

  useEffect(() => {
    fetchPlaylists()
  }, [])

  // 导航到歌单详情
  const navigateToPlaylist = (id) => {
    window.history.pushState({}, '', `/playlists/${id}`)
    const event = new PopStateEvent('popstate')
    window.dispatchEvent(event)
  }

  if (loading) {
    return <div className="main-content">加载中...</div>
  }

  return (
    <div className="main-content">
      <div className="page-header">
        <h1>我的歌单</h1>
        {isAuthenticated && (
          <button 
            className="btn btn-primary" 
            onClick={handleCreatePlaylist}
          >
            创建歌单
          </button>
        )}
      </div>

      {/* 搜索栏 */}
      <div className="search-container">
        <input
          type="text"
          placeholder="搜索歌单..."
          value={searchKeyword}
          onChange={(e) => setSearchKeyword(e.target.value)}
        />
        <button className="btn btn-primary" onClick={handleSearch}>
          搜索
        </button>
      </div>

      {error && <div className="error-message">{error}</div>}

      {/* 歌单列表 */}
      <div className="playlists-container">
        {playlists.length === 0 ? (
          <div className="empty-state">
            <p>暂无歌单</p>
            {isAuthenticated && (
              <button className="btn btn-primary" onClick={handleCreatePlaylist}>
                创建第一个歌单
              </button>
            )}
          </div>
        ) : (
          playlists.map(playlist => (
            <div key={playlist.id} className="playlist-item">
              <div className="playlist-info">
                <img 
                  src={`https://picsum.photos/seed/playlist${playlist.id}/100/100`} 
                  alt={playlist.name} 
                />
                <div>
                  <h3 onClick={() => navigateToPlaylist(playlist.id)}>{playlist.name}</h3>
                  <p>{playlist.songs?.length || 0} 首歌曲</p>
                </div>
              </div>
              
              {isAuthenticated && (
                <div className="playlist-actions">
                  <button 
                    className="btn btn-secondary" 
                    onClick={() => handleCopyPlaylist(playlist.id, playlist.name)}
                  >
                    复制
                  </button>
                  <button 
                    className="btn btn-danger" 
                    onClick={() => handleDelete(playlist.id)}
                  >
                    删除
                  </button>
                </div>
              )}
            </div>
          ))
        )}
      </div>
    </div>
  )
}

export default PlaylistsPage