import { createPortal } from 'react-dom';
import { useLocation } from 'react-router-dom';
import { NavLink } from 'react-router-dom';
import styled from '@emotion/styled';
import { TasksSvg, AdminPanelSvg, DictSvg } from '../common/icons/icons';
import { useAuth } from '../../app/context/AuthProvider';
import { ROLES_NAME_ID } from '../../constants';

const Switch = styled.div`
  margin-left: 1rem;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  height: 2rem;
`;

const Buttons = styled.div`
  width: max-content;
  height: 1rem;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  gap: 1rem;
`;

const StyledNavLink = styled(NavLink)`
  display: flex;
  gap: 0.625rem;
  align-items: center;
  border-radius: 0.5rem;
  padding: 0rem 0.75rem;
  cursor: pointer;
  height: 2rem;

  .img {
    svg {
      width: 1rem;
      height: 1rem;
    }
  }

  &.active {
    background-color: #f9fafb;
    span {
      color: #258141;
    }
  }
`;

export function HeaderSwitch() {
  const { user } = useAuth();
  const location = useLocation();
  const formsTasksPaths = ['/tasks', '/forms'];
  const adminPathsPrefix = '/admin_panel';
  const dictPaths = '/dicts-navigator';

  if (!user) return;

  const portalContent = (
    <Switch>
      <Buttons>
        <StyledNavLink
          to="/tasks"
          className={
            formsTasksPaths.includes(location.pathname) ? 'active' : ''
          }
        >
          <div className="img">
            <TasksSvg
              fill={
                formsTasksPaths.includes(location.pathname)
                  ? '#258141'
                  : '#99A1AF'
              }
            ></TasksSvg>
          </div>
          <span>Задачи</span>
        </StyledNavLink>
        {user.role_id === ROLES_NAME_ID.admin && (
          <StyledNavLink
            to="/admin_panel/users"
            className={
              location.pathname.startsWith(adminPathsPrefix) ? 'active' : ''
            }
          >
            <div className="img">
              <AdminPanelSvg
                fill={
                  location.pathname.startsWith(adminPathsPrefix)
                    ? '#258141'
                    : '#99A1AF'
                }
              />
            </div>
            <span>Администрирование</span>
          </StyledNavLink>
        )}
        <StyledNavLink
          to="/dicts-navigator"
          className={location.pathname.startsWith(dictPaths) ? 'active' : ''}
        >
          <div className="img">
            <DictSvg
              fill={
                location.pathname.startsWith(dictPaths) ? '#258141' : '#99A1AF'
              }
            />
          </div>
          <span>Справочники</span>
        </StyledNavLink>
      </Buttons>
    </Switch>
  );
  const targetElement = document.getElementById('TableInfo');
  if (targetElement) {
    return createPortal(portalContent, targetElement);
  }
}
