import React, { useState, useEffect, useRef } from "react";
import {
  addTrackToPlaylist,
  // setCurrentTrack
  deleteTrackFromPlaylist,
} from "../actions/playerActions";
import { connect } from "react-redux";
import { Spin } from "antd";

const AddTrack = ({
  myPlaylist,
  addTrackToPlaylist,
  deleteTrackFromPlaylist,
  // setCurrentTrack, currentTrack
}) => {
  // console.log('currentTrack in AddTrack: ', currentTrack);
  let ref = useRef();
  const [isLoading, setIsLoading] = useState(false);

  function upload(playlistId, playlist, form) {
    setIsLoading(true);
    let arrTracks = [];
    playlist.tracks &&
      playlist.tracks.map((item) => arrTracks.push({ ["_id"]: item._id }));

    console.log("arrTracks in upload: ", arrTracks);

    fetch("/track", {
      method: "POST",
      headers: localStorage.authToken
        ? { Authorization: "Bearer " + localStorage.authToken }
        : {},
      body: new FormData(form),
    })
      .then((res) => res.json()) //у чего есть then? у promise.
      .then(async (track) => {
        console.log("track: ", track);
        await addTrackToPlaylist(playlistId, arrTracks, track._id);
        setIsLoading(false);
      });
  }

  // function delete(playlistId, playlist, trackIndex){
  //   // let arrTracks = [];
  //   // playlist.tracks &&
  //   //   playlist.tracks.map((item) => arrTracks.push({ ["_id"]: item._id }));
  //     deleteTrackFromPlaylist(idPlaylist, arrTracks, trackIndex);
  // }

  return (
    <div className="my_tracks">
      <h2>My tracks in playlist {myPlaylist.name}</h2>
      <ul>
        {myPlaylist &&
          myPlaylist.tracks &&
          myPlaylist.tracks.map((track, index) => (
            <li key={index.toString()}>
              {track.originalFileName}
              <span
                onClick={() => {
                  console.log(index);
                  deleteTrackFromPlaylist(
                    localStorage.lastPLaylist,
                    myPlaylist,
                    index
                  );
                }}
              >
                X
              </span>
            </li>
          ))}
      </ul>
      <form
        action="/track"
        method="post"
        encType="multipart/form-data"
        id="trackForm"
        ref={ref}
      >
        <h2>Add track</h2>
        <input
          type="file"
          name="track"
          id="track"
          onChange={(e) => {
            console.log("ref: ", ref.current);
            upload(localStorage.lastPLaylist, myPlaylist, ref.current);
            // e.target.value = null
          }}
        />
        <Spin className="" spinning={isLoading} />
      </form>
    </div>
  );
};

const mapStateToProps = (state) => ({
  // newTrack: state.player.newTrack,
});

const mapDispatchtoProps = (dispatch) => ({
  addTrackToPlaylist: (idPlaylist, arrTracks, idTrack) =>
    dispatch(addTrackToPlaylist(idPlaylist, arrTracks, idTrack)),
  deleteTrackFromPlaylist: (idPlaylist, playlist, currentIndex) =>
    dispatch(deleteTrackFromPlaylist(idPlaylist, playlist, currentIndex)),
});

export default connect(mapStateToProps, mapDispatchtoProps)(AddTrack);
