import React from 'react'
import './playerControl.css'
import { FaPlayCircle } from "react-icons/fa";
import { FaPauseCircle } from "react-icons/fa";
import { FaShuffle } from "react-icons/fa6";
import { FaRepeat } from "react-icons/fa6";
import { IoPlaySkipForwardSharp } from "react-icons/io5"
import { IoPlaySkipBackSharp } from "react-icons/io5";
import { useStateProvider } from '../../../util/StateProvider';
import axios from 'axios';
import { reducerCases } from '../../../util/Constants';

export const PlayerControl = () => {
    const [{token, playerState}, dispatch] = useStateProvider();
    const changeTrack = async (type) => {
        await axios.post(`https://api.spotify.com/v1/me/player/${type}`,{}, 
        //PREMIUM_REQUIRED
        {
            headers: {
                Authorization:"Bearer "+token,
                "Content-Type": "application/json"
            }
        });
        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})
        }else
        dispatch({type: reducerCases.SET_PLAYING, currentlyPlaying: null})
    }
    
    const changeState = async () =>{
        const state = playerState ? "pause" : "play";
            await axios.put(`https://api.spotify.com/v1/me/player/${state}`,{},
        {
            headers: {
                Authorization:"Bearer "+token,
                "Content-Type": "application/json"
            }
        });
        dispatch({type: reducerCases.SET_PLAYER_STATE, playerState: !playerState})
    }
    
  return (
    <>
    <div className='PlayerControl'>
        <div className="playerControl-control">
            <div className="player-shuffle">
                <FaShuffle/>
            </div>
            <div className="player-prev">
                <IoPlaySkipBackSharp onClick={() => changeTrack("previous")}/>
            </div>
            <div className="player-state">
                {playerState ? <FaPauseCircle onClick={changeState}/> : <FaPlayCircle onClick={changeState}/>}
            </div>
            <div className="player-next">
                <IoPlaySkipForwardSharp onClick={() => changeTrack("next")}/>
            </div>
            <div className="play-repeat">
                <FaRepeat/>
            </div>
        </div>
        <div className="PlayerControl-play">
            <input type="range" value="0" id="progress"/>
        </div>
    </div>
    
   </> 
  )
}
