import { useState } from "react";
import PropTypes from "prop-types";
import { parse } from "cookie";
import { jwtDecode } from "jwt-decode";
import SanitizedContent from "../../SanitizedContent";
import AnimationGroup from "../AnimationGroup/AnimationGroup";
import SelectRole from "./SelectRole";
import { loadRoleOptions } from "./SelectRole/utils";

const LevelOneContent = ({ isExpanded, levelOneContent }) => {
  const {
    qpp_auth_token,
    qpp_has_authorizations: hasAuthorizations,
    qpp_cms_internal_authorized: cmsInternalRoleValues,
  } = parse(document.cookie);

  const roleOptions = loadRoleOptions([
    hasAuthorizations,
    cmsInternalRoleValues,
  ]);

  const [selectedRole, setSelectedRole] = useState("");

  let name = "";
  if (qpp_auth_token) {
    const { firstName, lastName } = jwtDecode(qpp_auth_token);
    name = `${firstName} ${lastName}`;
  }
  const path = window.location.pathname;
  document.cookie = `current_path=${path}; Path=/;`;

  const hasMultipleRoles = roleOptions.length > 1;

  return (
    <div className="sidebar-content">
      <AnimationGroup display={isExpanded}>
        <h1 className="label">{name}</h1>
      </AnimationGroup>
      <div className="level-one-nav animation-flat">
        {hasMultipleRoles && (
          <SelectRole
            selectedRole={selectedRole}
            setSelectedRole={setSelectedRole}
            roleOptions={roleOptions}
          />
        )}

        <SanitizedContent html={levelOneContent} />
      </div>
    </div>
  );
};

LevelOneContent.propTypes = {
  isExpanded: PropTypes.bool,
  levelOneContent: PropTypes.object,
};

export default LevelOneContent;
