import React, { useContext, useEffect, useState } from 'react';
import { GeneralStyledButton, ContentText } from './styles';
import { ThemeContext } from 'context/context';
import { theme } from 'data/dataMx';
import { IButtonProps, IthemeB } from '../ButtonProps';
import { getOnPrincipalColorFromTheme, getPrincipalColorFromTheme } from '../ButtonHelpers';
import { IFontWeight } from 'interfaces';

export const AtomButtonOutline = ({
  disabled,
  onPress,
  color,
  text,
  customColor = 'tertiary',
  width = '144px',
  size ='small',
  styles = {},
  groupStyle = 'normal',
  selected = false,
  ...props
}: IButtonProps) => {
  const { fontFamily } = useContext(ThemeContext);
  const font: string = fontFamily.main['regular' as keyof IFontWeight];

  const [themeB, setThemeB] = useState<IthemeB>({
    color: color === 'custom' ? theme[getPrincipalColorFromTheme(customColor)] : theme[color],
    backgroundColor: theme.transparent,
    borderWidth: 2,
    borderColor: `${color === 'custom' ? theme[getPrincipalColorFromTheme(customColor)] : theme[color]}`,
    width: width
  });

  const handlerPress = () => {
    onPress && onPress();
    setThemeB({
      ...themeB,
      color: color === 'custom'
        ? theme[getOnPrincipalColorFromTheme(customColor)]
        : color === 'primary'
          ? theme.primary300 : theme.secondary300,
      backgroundColor: theme.transparent,
      borderWidth: 4,
      borderColor: `${theme.tertiary100}`,
    })
  }

  const handlerPressOut = (fromUseEffect:boolean = false) => {
    if (disabled) {
      setThemeB({
        color: theme.neutral500,
        backgroundColor: theme.neutral200,
        borderWidth: 1,
        borderColor: `${theme.neutral400}`,
        width: width
      })
      return
    }
    if (groupStyle === 'toggle' && fromUseEffect) {
      setThemeB({
        color: selected? theme.neutral100: theme.neutral700,
        backgroundColor: selected? theme.primary: theme.transparent,
        borderWidth: selected? 2: 0,
        width: 'auto'
      })
      return
    }
    setThemeB({
      color: color === 'custom' ? theme[getPrincipalColorFromTheme(customColor)] : theme[color],
      backgroundColor: theme.transparent,
      borderWidth: 2,
      borderColor: `${color === 'custom' ? theme[getPrincipalColorFromTheme(customColor)] : theme[color]}`,
      width: width
    })
  }

  useEffect(() => {
    handlerPressOut(true);
  }, [disabled, color, width, customColor, selected]);

  return (
    <GeneralStyledButton
      disabled={disabled}
      onPress={() => !disabled && handlerPress()}
      onPressOut={() => handlerPressOut()}
      delayPressOut={1000}
      theme={themeB}
      testID={'out-btn'}
      activeOpacity={100}
      font={font}
      size={size}
      styles={styles}
      {...props}
    >
      <ContentText
        theme={themeB}
        font={font}
        size={size}
      >
        {text}
      </ContentText>
    </GeneralStyledButton>
  );
};
