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

function PlaylistDetailPage({ onPlaySong, playlistId }) {
  const { isAuthenticated } = useAuth()
  const [playlist, setPlaylist] = useState(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)
  const [songToAdd, setSongToAdd] = useState({
    title: '',
    artist: '',
    genre: ''
  })
  const [isAdding, setIsAdding] = useState(false)

  // 获取歌单详情
  const fetchPlaylist = async () => {
    try {
      setLoading(true)
      const data = await playlistAPI.getById(playlistId)
      setPlaylist(data)
    } catch (err) {
      setError('无法加载歌单详情，请稍后再试')
      console.error('Error fetching playlist:', err)
    } finally {
      setLoading(false)
    }
  }

  // 添加歌曲到歌单
  const handleAddSong = async (e) => {
    e.preventDefault()
    if (!songToAdd.title || !songToAdd.artist) return

    try {
      await songAPI.addToPlaylist(playlistId, songToAdd)
      fetchPlaylist() // 重新加载歌单
      setSongToAdd({ title: '', artist: '', genre: '' })
      setIsAdding(false)
    } catch (err) {
      setError('添加歌曲失败，请稍后再试')
      console.error('Error adding song:', err)
    }
  }

  // 从歌单移除歌曲
  const handleRemoveSong = async (songId) => {
    if (window.confirm('确定要从歌单中移除这首歌曲吗？')) {
      try {
        await songAPI.removeFromPlaylist(playlistId, songId)
        fetchPlaylist() // 重新加载歌单
      } catch (err) {
        setError('移除歌曲失败，请稍后再试')
        console.error('Error removing song:', err)
      }
    }
  }

  // 更新歌单信息
  const handleUpdatePlaylist = () => {
    const newName = prompt('请输入新歌单名称：', playlist.name)
    if (newName && newName.trim() && newName.trim() !== playlist.name) {
      updatePlaylist(newName.trim())
    }
  }

  // 更新歌单API调用
  const updatePlaylist = async (name) => {
    try {
      const updated = await playlistAPI.update(playlistId, { name })
      setPlaylist(updated)
    } catch (err) {
      setError('更新歌单失败，请稍后再试')
      console.error('Error updating playlist:', err)
    }
  }

  useEffect(() => {
    fetchPlaylist()
  }, [playlistId])

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

  if (error || !playlist) {
    return <div className="main-content">{error || '歌单不存在'}</div>
  }

  return (
    <div className="main-content">
      <div className="playlist-header">
        <div className="playlist-cover">
          <img 
            src={`https://picsum.photos/seed/playlist${playlist.id}/400/400`} 
            alt={playlist.name} 
          />
        </div>
        <div className="playlist-meta">
          <h1>{playlist.name}</h1>
          <p>{playlist.songs?.length || 0} 首歌曲</p>
          {isAuthenticated && (
            <div className="playlist-actions">
              <button 
                className="btn btn-primary" 
                onClick={handleUpdatePlaylist}
              >
                编辑信息
              </button>
              {isAdding ? (
                <button 
                  className="btn btn-secondary" 
                  onClick={() => setIsAdding(false)}
                >
                  取消
                </button>
              ) : (
                <button 
                  className="btn btn-secondary" 
                  onClick={() => setIsAdding(true)}
                >
                  添加歌曲
                </button>
              )}
            </div>
          )}
        </div>
      </div>

      {/* 添加歌曲表单 */}
      {isAdding && isAuthenticated && (
        <div className="add-song-form-container">
          <h2>添加歌曲</h2>
          <form onSubmit={handleAddSong} className="add-song-form">
            <div className="form-group">
              <label htmlFor="title">歌曲标题</label>
              <input
                type="text"
                id="title"
                value={songToAdd.title}
                onChange={(e) => setSongToAdd(prev => ({ ...prev, title: e.target.value }))}
                required
              />
            </div>
            <div className="form-group">
              <label htmlFor="artist">歌手</label>
              <input
                type="text"
                id="artist"
                value={songToAdd.artist}
                onChange={(e) => setSongToAdd(prev => ({ ...prev, artist: e.target.value }))}
                required
              />
            </div>
            <div className="form-group">
              <label htmlFor="genre">流派</label>
              <input
                type="text"
                id="genre"
                value={songToAdd.genre}
                onChange={(e) => setSongToAdd(prev => ({ ...prev, genre: e.target.value }))}
              />
            </div>
            <div className="form-actions">
              <button type="submit" className="btn btn-primary">添加</button>
              <button 
                type="button" 
                className="btn btn-secondary" 
                onClick={() => setIsAdding(false)}
              >
                取消
              </button>
            </div>
          </form>
        </div>
      )}

      {/* 歌曲列表 */}
      <div className="songs-container">
        <h2>歌曲列表</h2>
        {playlist.songs && playlist.songs.length > 0 ? (
          <table className="songs-table">
            <thead>
              <tr>
                <th>标题</th>
                <th>歌手</th>
                <th>流派</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {playlist.songs.map((song, index) => (
                <tr key={song.id}>
                  <td>
                    <div className="song-title">
                      <button 
                        className="play-btn-small" 
                        onClick={() => onPlaySong(song)}
                      >
                        ▶
                      </button>
                      {song.title}
                    </div>
                  </td>
                  <td>{song.artist}</td>
                  <td>{song.genre || '未知'}</td>
                  <td>
                    {isAuthenticated && (
                      <button 
                        className="btn btn-danger btn-small" 
                        onClick={() => handleRemoveSong(song.id)}
                      >
                        删除
                      </button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        ) : (
          <div className="empty-state">
            <p>歌单中还没有歌曲</p>
            {isAuthenticated && (
              <button 
                className="btn btn-primary" 
                onClick={() => setIsAdding(true)}
              >
                添加第一首歌曲
              </button>
            )}
          </div>
        )}
      </div>
    </div>
  )
}

export default PlaylistDetailPage