import React, {  useEffect, useState } from "react";
import {  connect } from "react-redux";
import { Spin } from "antd";
import Header from "./Header";
import Footer from "./Footer";

import AddTrackFromLibToPlaylist from "./AddTrackFromLibToPlaylist";
import Player from "./Player";
import { getTracks, setCurrentTrack, findUser } from "../actions/playerActions";

import "../styles/library.css";

const Lib = ({
  tracks,
  history,
  getTracks,
  login,
  setCurrentTrack,
  currentTrack,
  findUser,
  // state
}) => {
const [checkPlaylist, setCheckPlaylist] = useState(false)

  useEffect(() => {
    getTracks && getTracks()
     && findUser && findUser(login);
  }, []);

  const Track = ({ track, highlighted }) => {
    const { originalFileName, url, _id, trackIndex } = track;
    return (
      <li
        className={highlighted ? "highlighted" : null}
        onClick={(e) => {
          setCurrentTrack(trackIndex);
        }}
      >
        <p>
          <span>{originalFileName}</span>
          <span onClick={() => {
            console.log("TODO action");
            setCheckPlaylist(!checkPlaylist);
        }}>+</span>
        </p>
      </li>
    );
  };

  const TrackList = ({ playlist, currentTrack }) => {
    console.log("playlist in library: ", playlist);
    return (
      <div className="main">
        <div className="trackList">
          <ul>
            {/* trackIndex это порядковый номер объекта в массиве */}
            {playlist.map((track, trackIndex) =>
              track.originalFileName && track.url && track._id !== null ? (
                <Track
                  key={trackIndex}
                  track={{ ...track, trackIndex }}
                  highlighted={trackIndex === currentTrack}
                />
              ) : (
                ""
              )
            )}
          </ul>
          <Player playlist={tracks} />
        </div>
      </div>
    );
  };

  return (
    <div className="wrapper">
      <Header login={login} />
      {!tracks.length && (
        <div className="container">
          <Spin size="large" tip="loading..." />
        </div>
      )}
      <TrackList playlist={tracks} currentTrack={currentTrack} />
     {checkPlaylist?
     <AddTrackFromLibToPlaylist />
     : ''
      } 
      <Footer />
    </div>
  );
};

const mapStateToProps = (state) => ({
  tracks: state.player.tracks,
  currentTrack: state.player.currentTrack,
  login: (state.auth.data.data && state.auth.data.data.sub.login) || "",
});

const mapDispatchToProps = (dispatch) => ({
  getTracks: () => setTimeout(() => dispatch(getTracks()), 2000),
  setCurrentTrack: (trackIndex) => dispatch(setCurrentTrack(trackIndex)),
  findUser: (login) => dispatch(findUser(login)),
});

export default connect(mapStateToProps, mapDispatchToProps)(Lib);
