import React, { useEffect } from 'react'
import './playList.css'
import {useStateProvider} from '../../util/StateProvider'
import axios from 'axios'
import { reducerCases } from '../../util/Constants'

const PlayList = () => {
    const [{token, playlists}, dispatch] = useStateProvider();
    useEffect(() => {
        const getPlaylist = async () =>{
            const response = await axios.get('https://api.spotify.com/v1/me/playlists', {
                headers: {
                    Authorization:"Bearer "+token,
                    "Content-Type": "application/json"
                }
            });
            const {items} = response.data
            const playlists = items.map(({name, id, images}) =>{
                return {name, id, images}
            });
            dispatch({type: reducerCases.SET_PLAYLIST, playlists})
        }
        getPlaylist();
    }, [token, dispatch])

    const changeCurrentPlaylist = (selectedPlaylistId) =>{
        dispatch({type: reducerCases.SET_PLAYLIST_ID,selectedPlaylistId});
    }


  return (
    <div className='Playlist'>
        <ul>
            {
                playlists.map(({name, id, images}) => {
                    console.log(playlists)
                    return(
                        <div className='playlist-side'>
                            <img src={images[0].url} alt="" />
                            <li key={id} onClick={() => changeCurrentPlaylist(id)}>{name}</li>
                        </div>
                    )
                })
            }
        </ul>
    </div>
  )
}

export default PlayList