import React from 'react';
import styled from 'styled-components';

import type { JSX } from 'react';

import { useThemeConfig, useThemeHooks } from '@redocly/theme/core/hooks';
import { UserAvatar } from '@redocly/theme/components/UserMenu/UserAvatar';
import { LogoutMenuItem } from '@redocly/theme/components/UserMenu/LogoutMenuItem';
import { LoginButton } from '@redocly/theme/components/UserMenu/LoginButton';

export type UserMenuMobileProps = {
  className?: string;
};

export function UserMenuMobile({ className }: UserMenuMobileProps): JSX.Element | null {
  const { useUserMenu } = useThemeHooks();
  const { userData, loginUrl } = useUserMenu();
  const { userMenu: userMenuSettings } = useThemeConfig();

  if (!userData?.isAuthenticated) {
    if (loginUrl && !userMenuSettings?.hideLoginButton) {
      return (
        <UserMenuMobileWrapper data-component-name="UserMenu/UserMenuMobile" className={className}>
          <UserMenuMobileLoginButton href={loginUrl} />
        </UserMenuMobileWrapper>
      );
    } else {
      return null;
    }
  }

  return (
    <UserMenuMobileWrapper data-component-name="UserMenu/UserMenuMobile" className={className}>
      <UserInfoWrapper>
        <UserAvatar picture={userData.picture} />
        <div>{userData.name}</div>
      </UserInfoWrapper>
      <LogoutMenuItem iconOnly />
    </UserMenuMobileWrapper>
  );
}

const UserMenuMobileWrapper = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  bottom: 0;
  padding: 18px 16px;
  border-top: 1px solid var(--menu-mobile-profile-border-color);
  background: var(--menu-mobile-profile-bg-color);
`;

const UserMenuMobileLoginButton = styled(LoginButton)`
  width: 100%;

  & button {
    width: 100%;
  }
`;

const UserInfoWrapper = styled.div`
  display: flex;
  align-items: center;
  gap: var(--spacing-base);
`;
