import React, { MouseEventHandler } from 'react';

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

import { mq } from '../../breakpoints';
import { useOnElementClick } from '../../on-element-click-provider';
import { linkDisabledStyle } from '../../styles';
import { CurrentProjectInterface, NavElement } from '../../types';
import {
  activeTriggerStyle,
  activeTriggerThemeStyle,
  baseTriggerStyle,
  buttonTextStyle,
  disabledTriggerBaseStyle,
  disabledTriggerThemeStyle,
  themeTriggerStyle,
} from '../styles';

const projectTriggerStyle = css`
  border-color: transparent;

  ${mq({
    width: ['172px', '106px', '106px'],
    height: ['30px', '36px', '36px'],
  })}
`;

interface ProjectSelectTriggerProps
  extends HTMLElementProps<'button', HTMLButtonElement> {
  onClick: MouseEventHandler<Element>;
  loading: boolean;
  open: boolean;
  current?: CurrentProjectInterface;
}

export const ProjectSelectTrigger = React.forwardRef<
  HTMLButtonElement,
  ProjectSelectTriggerProps
>(
  (
    {
      onClick,
      loading,
      open,
      current,
      disabled: disabledProp,
      ...rest
    }: ProjectSelectTriggerProps,
    forwardedRef,
  ) => {
    const { theme } = useDarkMode();

    const onElementClick = useOnElementClick();
    const buttonRef = useForwardedRef(forwardedRef, null);
    const isDisabled = loading || disabledProp;

    return (
      <Button
        {...rest}
        ref={buttonRef}
        data-testid="project-select-trigger"
        disabled={isDisabled}
        aria-disabled={isDisabled}
        aria-expanded={open}
        onClick={onElementClick(
          NavElement.ProjectNavProjectSelectTrigger,
          onClick,
        )}
        className={cx(
          baseTriggerStyle,
          themeTriggerStyle[theme],
          projectTriggerStyle,
          {
            [cx(activeTriggerStyle, activeTriggerThemeStyle[theme])]: open,
            [cx(disabledTriggerBaseStyle, disabledTriggerThemeStyle[theme])]:
              isDisabled,
          },
        )}
        leftGlyph={<FolderIcon role="presentation" />}
        rightGlyph={<CaretDownIcon role="presentation" size="small" />}
      >
        <span
          className={cx(buttonTextStyle, { [linkDisabledStyle]: isDisabled })}
          data-testid="project-select-active-project"
        >
          {current?.projectName ?? 'Select Project'}
        </span>
      </Button>
    );
  },
);

ProjectSelectTrigger.displayName = 'ProjectSelectTrigger';
