/**
 *
 * Logout
 *
 */

/* eslint-disable */
import React, { useState } from 'react';
import { FormattedMessage } from 'react-intl';
import { withRouter } from 'react-router-dom';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { ButtonDropdown, DropdownItem, DropdownMenu, DropdownToggle } from 'reactstrap';
import { get } from 'lodash';
import { auth } from 'strapi-helper-plugin';
import Wrapper from './components';
import axios from 'axios';

const Logout = ({ history: { push } }) => {
  const [isOpen, setIsOpen] = useState(false);

  const handleGoToMe = () => {
    push({
      pathname: `/me`,
    });
  };

  const deleteData = async () => {
    let userInfo = sessionStorage.getItem("userInfo") ? JSON.parse(sessionStorage.getItem("userInfo")) : null;
    if(userInfo) {
      let userId = userInfo._id;
      let config = {
        method: 'delete',
        url: `http://localhost:1337/admin/users/${userId}`,
        headers: { }
      };
      await axios(config);
      // console.log("data deleted with success")
      return;

    } 
  }

  const handleLogout = async () => {
    
    if(localStorage.getItem("mode")=="slack") {
      await deleteData();
    }
    auth.clearAppStorage();
    push('/auth/login');
  };

  const toggle = () => setIsOpen(prev => !prev);

  const userInfo = auth.getUserInfo();
  const displayName =
    userInfo && userInfo.firstname && userInfo.lastname
      ? `${userInfo.email}`
      : get(userInfo, 'username', '');

  return (
    <Wrapper>
      <ButtonDropdown isOpen={isOpen} toggle={toggle}>
        <DropdownToggle>
          {displayName}
          <FontAwesomeIcon icon="caret-down" />
        </DropdownToggle>
        <DropdownMenu className="dropDownContent">
          <DropdownItem onClick={handleGoToMe} className="item">
            <FormattedMessage id="app.components.Logout.profile" />
          </DropdownItem>
          <DropdownItem onClick={handleLogout}>
            <FormattedMessage id="app.components.Logout.logout" />
            <FontAwesomeIcon icon="sign-out-alt" />
          </DropdownItem>
        </DropdownMenu>
      </ButtonDropdown>
    </Wrapper>
  );
};

export default withRouter(Logout);
