import React from 'react';
import PropTypes from 'prop-types';

import { css, cx } from '@leafygreen-ui/emotion';
// @ts-expect-error
import MagnifyingGlassIcon from '@leafygreen-ui/icon/dist/MagnifyingGlass';
import { useDarkMode } from '@leafygreen-ui/leafygreen-provider';
import { HTMLElementProps, Theme } from '@leafygreen-ui/lib';
import { palette } from '@leafygreen-ui/palette';
import TextInput from '@leafygreen-ui/text-input';

import { Variant } from '../../types';

type InputProps = HTMLElementProps<'input'> & {
  onChange: React.ChangeEventHandler;
  onKeyDown: React.KeyboardEventHandler;
  variant: Variant;
};

const liStyle = css`
  position: relative;
`;

const inputBaseStyle = css`
  // Input does not yet support adding an icon on the left
  & input {
    padding-left: 32px;
  }
`;

const inputThemeStyle: Record<Theme, string> = {
  [Theme.Dark]: css`
    input {
      &:hover:not(:disabled):not(:focus) {
        box-shadow: 0px 0px 0px 3px ${palette.gray.light1};
      }

      &::placeholder {
        color: ${palette.gray.base};
      }
    }
  `,
  [Theme.Light]: css`
    input {
      &::placeholder {
        color: ${palette.gray.light1};
      }
    }
  `,
};

const iconBaseStyle = css`
  position: absolute;
  height: 16px;
  width: 16px;
  top: 6px;
  left: 8px;
`;

const iconThemeStyle: Record<Theme, string> = {
  [Theme.Light]: css`
    color: ${palette.gray.light1};
  `,
  [Theme.Dark]: css`
    color: ${palette.gray.base};
  `,
};

const MongoSelectInput = React.forwardRef(
  (
    { variant, value, onChange, onKeyDown, className, ...rest }: InputProps,
    ref,
  ) => {
    const { darkMode, theme } = useDarkMode();

    const placeholderVariant =
      variant === Variant.Organization ? 'an Organization' : 'a Project';
    const placeholder = `Search for ${placeholderVariant}...`;

    return (
      <li className={cx(liStyle, className)} role="none">
        <TextInput
          {...rest}
          darkMode={!darkMode}
          sizeVariant="small"
          onChange={onChange}
          onKeyDown={onKeyDown}
          value={value?.toString()}
          placeholder={placeholder}
          ref={ref as React.RefObject<HTMLInputElement>}
          aria-label={placeholder}
          type="search"
          className={cx(inputBaseStyle, inputThemeStyle[theme])}
        />
        <MagnifyingGlassIcon
          className={cx(iconBaseStyle, iconThemeStyle[theme])}
        />
      </li>
    );
  },
);

MongoSelectInput.displayName = 'MongoSelectInput';

MongoSelectInput.propTypes = {
  onChange: PropTypes.func.isRequired,
  onKeyDown: PropTypes.func.isRequired,
};

export default MongoSelectInput;
