import React, { useRef, InputHTMLAttributes, useImperativeHandle } from 'react';
import { useTheme } from 'styled-components';
import { ITheme, ThemeDefault } from '../../types/theme.interface';
import { FormStyle } from '../styles';
import { ISwitchProps, ISwitchPureComponentProps } from './Switch.interface';
import Style from './Switch.style';
import { SwitchCore } from './SwitchCore';

export const SwitchPure = React.forwardRef<InputHTMLAttributes<any>, ISwitchPureComponentProps>(function SwitchPure(
   props,
   inputRef: any,
) {
   // default theme
   const theme = useTheme() as ITheme;
   const { checkbox = {} } = theme ?? {};
   const { defaultColor: defaultColorTheme, size: sizeTheme, rounded: roundedTheme } = checkbox as ITheme['checkbox'];

   const {
      title,
      color,
      checked,
      rounded = roundedTheme,
      size = sizeTheme ?? 24,
      variant = 'primary',
      valueTrue = true,
      valueFalse = false,
      error,
      disabled = false,
      onChange,
      ...rest
   } = props;
   const ref = useRef(null);
   useImperativeHandle(inputRef, () => ref.current, []);

   const checkboxColor =
      color ?? defaultColorTheme ?? (theme ?? {})[variant] ?? ThemeDefault[variant] ?? ThemeDefault.primary;

   return (
      <FormStyle>
         <Style color={checkboxColor} rounded={rounded} size={size}>
            <div className="checkbox-container clean">
               <label className="checkbox-container clean">
                  <input
                     ref={ref}
                     type="checkbox"
                     checked={checked}
                     disabled={disabled}
                     {...rest}
                     onChange={(e) => {
                        if (onChange) onChange(e.currentTarget.checked ? valueTrue : valueFalse);
                     }}
                  />
                  <span
                     className={`checkbox ${error && 'has-error'} ${disabled && 'disabled'}`}
                     data-testid="input-checkbox-error"
                  />
                  <span className={`title ${disabled && 'disabled'}`}>{title}</span>
               </label>
            </div>

            {error && (
               <div className="error-input" data-testid="input-error">
                  {error}
               </div>
            )}
         </Style>
      </FormStyle>
   );
});

export const Switch = React.forwardRef<InputHTMLAttributes<any>, ISwitchProps>(function Switch(props, inputRef: any) {
   return <SwitchCore {...props} ref={inputRef} as={SwitchPure} />;
});
