import React, { InputHTMLAttributes } from 'react';

import InputUnstyled from '@mui/base/InputUnstyled';

import { bem } from 'utils/bem';

import { Icon, ICON_SIZE } from '../Icon/Icon';
import { Typography, TYPOGRAPHY_TYPE } from '../Typography';
import { Button, BUTTON_SIZE, BUTTON_TYPE } from '../Button';
import { THEME } from '../../constants';
import { INPUT_VARIANT } from './types';

import styles from './input.scss';

export interface IInputProps extends InputHTMLAttributes<HTMLInputElement> {
  theme?: THEME;
  variant?: INPUT_VARIANT;
  className?: string;
  inputClassName?: string;
  error?: string;
  label?: React.ReactNode;
  icon?: string;
  isClearable?: boolean;
  onClearClick?(): void;
}

const rootClassName = bem(styles, 'input');

export const Input = React.forwardRef<HTMLDivElement, IInputProps>(
  (
    {
      theme = THEME.dark,
      variant = INPUT_VARIANT.default,
      className,
      inputClassName,
      error,
      label,
      icon,
      isClearable = false,
      onClearClick,
      disabled = false,
      ...restProps
    },
    ref,
  ) => {
    return (
      <div
        className={rootClassName(
          null,
          {
            [theme]: true,
            isClearable,
            isDisabled: disabled,
            isCompact: variant === INPUT_VARIANT.compact,
            hasIcon: Boolean(icon),
          },
          className,
        )}
        ref={ref}
      >
        {label && (
          <Typography
            className={rootClassName('label')}
            type={TYPOGRAPHY_TYPE.body3}
          >
            {label}
          </Typography>
        )}

        <InputUnstyled
          className={rootClassName('container', { isError: Boolean(error) }, inputClassName)}
          slots={{ root: 'label' }}
          slotProps={{ input: { ...restProps, className: rootClassName('field') } }}
          disabled={disabled}
          error={Boolean(error)}
          startAdornment={
            icon && (
              <Icon
                className={rootClassName('icon', { isDisabled: disabled })}
                name={icon}
                size={ICON_SIZE.medium}
              />
            )
          }
          endAdornment={
            isClearable && (
              <Button
                className={rootClassName('clear')}
                theme={theme}
                type={BUTTON_TYPE.tertiary}
                size={BUTTON_SIZE.smallRound}
                icon="cross"
                onClick={onClearClick}
              />
            )
          }
        />

        {error && (
          <Typography
            className={rootClassName('error')}
            type={TYPOGRAPHY_TYPE.body4}
          >
            {error}
          </Typography>
        )}
      </div>
    );
  },
);

Input.displayName = 'Input';
