import React, { MouseEventHandler } from 'react';

import Button from '@leafygreen-ui/button';
import { css, cx } from '@leafygreen-ui/emotion';
import { useForwardedRef, useViewportSize } from '@leafygreen-ui/hooks';
// @ts-expect-error
import CaretDownIcon from '@leafygreen-ui/icon/dist/CaretDown';
import { useDarkMode } from '@leafygreen-ui/leafygreen-provider';

import { breakpoints } from '../../breakpoints';
import { useOnElementClick } from '../../on-element-click-provider';
import { NavElement } from '../../types';

import {
  disabledTriggerBaseStyle,
  disabledTriggerThemeStyle,
  menuNameStyle,
  menuTriggerBaseStyle,
  menuTriggerThemeStyle,
  openTriggerBaseStyle,
  openTriggerThemeStyle,
} from './UserMenuTrigger.styles';

interface UserMenuTriggerProps {
  name: string;
  open: boolean;
  onClick: MouseEventHandler<Element>;
  loading?: boolean;
}

export const UserMenuTrigger = React.forwardRef<
  HTMLButtonElement,
  UserMenuTriggerProps
>(
  (
    { open, name, onClick, loading, ...rest }: UserMenuTriggerProps,
    forwardedRef,
  ) => {
    const { theme } = useDarkMode();
    const onElementClick = useOnElementClick();
    const viewportSize = useViewportSize();
    const buttonRef = useForwardedRef(forwardedRef, null);

    const isTablet = viewportSize
      ? viewportSize.width < breakpoints.medium
      : false;

    // Show first initial on tablets and smaller, otherwise use the full name passed in
    const displayName = isTablet ? name.split('')[0] : name;

    const activeWidth = css`
      width: ${buttonRef?.current?.getBoundingClientRect().width}px;
    `;

    return (
      <Button
        {...rest}
        ref={buttonRef}
        disabled={loading}
        aria-expanded={open}
        onClick={onElementClick(NavElement.UserMenuTrigger, onClick)}
        className={cx(menuTriggerBaseStyle, menuTriggerThemeStyle[theme], {
          [cx(openTriggerBaseStyle, openTriggerThemeStyle[theme])]: open,
          [activeWidth]: open,
          [cx(disabledTriggerBaseStyle, disabledTriggerThemeStyle[theme])]:
            loading,
        })}
        rightGlyph={<CaretDownIcon role="presentation" />}
      >
        <span className={menuNameStyle}>{displayName}</span>
      </Button>
    );
  },
);

UserMenuTrigger.displayName = 'UserMenuTrigger';
