import React, { useState, useEffect, Component } from "react";
import { Link } from "react-router-dom";
import { Provider, connect } from "react-redux";
import { createStore, combineReducers, applyMiddleware } from "redux";
import { render } from "react-dom";
import { Spin } from "antd";
import Header from "./Header";
import Footer from "./Footer";

import App from "../App";
import Player from "./Player";
import getGQL from "../utils/getGQL";
import { getTracks, setCurrentTrack } from "../actions/playerActions";

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

const Lib = ({
  tracks,
  history,
  getTracks,
  login,
  setCurrentTrack,
  currentTrack,
}) => {
  useEffect(() => {
    getTracks && getTracks();
  }, []);

  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")}>+</span>
        </p>
      </li>
    );
  };

  const TrackList = ({ playlist, currentTrack }) => {
    console.log(playlist);
    return (
      <div className="main">
        <div className="trackList">
          <ul>
            {playlist.map((track, trackIndex) => (
              <Track
                key={trackIndex}
                track={{ ...track, trackIndex }}
                highlighted={trackIndex === currentTrack}
              />
              // console.log(track)
            ))}
          </ul>
          <Player playlist={tracks} />
        </div>
      </div>
    );
  };

  return (
    <>
      <Header login={login} />
      {!tracks.length && (
        <div className="container">
          <Spin size="large" />
        </div>
      )}
      <TrackList playlist={tracks} currentTrack={currentTrack} />
      <Footer />
    </>
  );
};

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: () => dispatch(getTracks()),
  setCurrentTrack: (trackIndex) => dispatch(setCurrentTrack(trackIndex)),
});

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