import React, { useEffect } from 'react'
import './currentTrack.css'
import { useStateProvider } from '../../../util/StateProvider'
import axios from 'axios';
import { reducerCases } from '../../../util/Constants';
import { CiHeart } from "react-icons/ci";

const CurrentTrack = () => {
    const [{token, currentlyPlaying}, dispatch] = useStateProvider();
    useEffect(() => {
        const getcurrentTrack = async () =>{
            const response = await axios.get('https://api.spotify.com/v1/me/player/currently-playing', {
                headers: {
                    Authorization:"Bearer "+token,
                    "Content-Type": "application/json"
                }
            });
            if(response.data !== ""){
                const {item} = response.data;
                const currentlyPlaying = {
                    id: item.id,
                    name: item.name,
                    artists: item.artists.map((artist) => artist.name),
                    image: item.album.images[2].url,
                };
                dispatch({type: reducerCases.SET_PLAYING, currentlyPlaying})
            }
        }
        getcurrentTrack();
    }, [token, dispatch, currentlyPlaying])



  return (
    <div className='CurrentTrack'>
        {
            currentlyPlaying && (
                <div className="track">
                    <div className="track-image">
                        <img src={currentlyPlaying.image} alt="currentlyplaying" />
                    </div>
                    <div className="track-info">
                        <p>{currentlyPlaying.name}</p>
                        <span>{currentlyPlaying.artists.join(", ")}</span>
                    </div>
                    <div className="track-fav">
                        <CiHeart/>
                    </div>
                </div>
            )
        }
    </div>
  )
}

export default CurrentTrack