import { css } from 'glamor';
import { Button } from '../Button';
import { BsFillEyeFill } from 'react-icons/bs';
import { HTMLInputTypeAttribute } from 'react';
import { InputToggleTypeButtonStyles } from './input.styles.interface';
import { getComponentButtonInputToggleStyles } from './input.component.styles';
import { useApphouse } from '../../context/useApphouse';
import { observer } from 'mobx-react';
import React from 'react';
import {
  BoxSizeStyles,
  ButtonStyleVariant
} from '../../styles/defaults/themes.interface';
import { merge } from '../../utils/obj/merge';

/**
 * Interface for the ButtonToggleInputType component
 * A private component used by the Input component
 */
export interface InputToggleTypeButtonProps {
  /**
   * A function that is called when the button is clicked
   * @param type
   * @returns
   */
  onToggle: (type: HTMLInputTypeAttribute) => void;
  /**
   * The type of the input
   */
  type: HTMLInputTypeAttribute;
  /**
   * Styles to be applied to the button
   * @default 'clear'
   * @optional
   */
  styleOverwrites?: InputToggleTypeButtonStyles;
  /**
   * If provided, the button will be rendered with this
   * icon instead of the default one
   * @optional
   */
  icon?: React.ReactNode;
  /**
   * The variant of the input
   * @default 'm'
   */
  variant?: keyof ButtonStyleVariant;
  /**
   * The size of the input
   */
  size?: keyof BoxSizeStyles;
}
/**
 * A private  button component used by the Input component
 * @param InputToggleTypeButtonProps
 * @returns a react component that renders a button with a wrapper
 */
export const InputToggleTypeButton = observer(
  React.forwardRef(
    (props: InputToggleTypeButtonProps, ref?: React.Ref<HTMLButtonElement>) => {
      const {
        onToggle,
        type,
        styleOverwrites,
        size = 'm',
        icon,
        variant = 'clear'
      } = props;
      const { theme } = useApphouse();
      const { tokens } = theme;
      const localStyles = merge(
        {},
        getComponentButtonInputToggleStyles(theme, size),
        styleOverwrites
      );

      const iconSize = tokens.iconSize[size];

      return (
        <div
          data-xray="ButtonToggleInputType"
          data-style="wrapper"
          {...css(localStyles.wrapper)}
        >
          <Button
            ref={ref}
            onClick={() => {
              const iType = type === 'password' ? 'text' : 'password';
              onToggle(iType);
            }}
            variant={variant}
            size={size}
            styleOverwrites={localStyles.button}
          >
            {icon && icon}
            {!icon && <BsFillEyeFill size={iconSize} />}
          </Button>
        </div>
      );
    }
  )
);
