import React, { Component } from "react";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import { Dropdown, Menu } from "semantic-ui-react";

import { sendGetSelfUserRequest } from "../actions/user/saga.actions";
import { sendLogoutRequest } from "../actions/auth/saga.actions";

class Navbar extends Component {
  componentWillMount() {
    const { dispatch, userToken, selfUser } = this.props;
    // If the user token exists and the self user object isn't loaded, dispatch
    if (userToken && Object.keys(selfUser).length === 0) {
      dispatch(sendGetSelfUserRequest());
    }
  }

  dispatchLogoutRequest = () => {
    this.props.dispatch(sendLogoutRequest());
  };

  render() {
    const { userToken } = this.props;
    return (
      <NavbarView
        isAuthenticated={!!userToken}
        dispatchLogoutRequest={this.dispatchLogoutRequest}
      />
    );
  }
}

function mapStateToProps(state) {
  return {
    userToken: state.auth.userToken,
    selfUser: state.user.selfUser
  };
}

const NavbarView = ({ isAuthenticated, dispatchLogoutRequest }) => (
  <Menu>
    <Menu.Item as={Link} to="/">
      Caremyway
    </Menu.Item>
    <Menu.Item as={Link} to="/about">
      About
    </Menu.Item>
    {!isAuthenticated &&
      <Menu.Menu position="right">
        <Menu.Item as={Link} to="/auth/login">
          Login
        </Menu.Item>
        <Menu.Item as={Link} to="/auth/register">
          Register
        </Menu.Item>
      </Menu.Menu>}
    {!!isAuthenticated &&
      <Menu.Menu position="right">
        <Dropdown item text="Account">
          <Dropdown.Menu>
            <Dropdown.Item as={Link} to="/user/profile">
              My Profile
            </Dropdown.Item>
            <Dropdown.Item as={Link} to="/auth/settings">
              Settings
            </Dropdown.Item>
            <Dropdown.Divider />
            <Dropdown.Item onClick={dispatchLogoutRequest}>
              Logout
            </Dropdown.Item>
          </Dropdown.Menu>
        </Dropdown>
      </Menu.Menu>}
  </Menu>
);

export default connect(mapStateToProps)(Navbar);
