import React, { FC, useContext } from 'react';
import { TouchableOpacity, View } from 'react-native';
import { SwitchProps } from './types';
import styles from './styles';
import { Colors } from '../Consts';
import { useComponentId } from '../Application';
import { ComponentContext, MiniAppContext } from '../Context';

const Switch: FC<SwitchProps> = ({
  value = false,
  onChange,
  disabled = false,
  style,
  params,
  accessibilityLabel,
  ...props
}) => {
  const context = useContext<any>(MiniAppContext);
  const circleBackgroundColor = value ? Colors.black_01 : Colors.black_03;
  const circleAlign = value ? 'flex-end' : 'flex-start';
  const componentName = 'Switch';

  const { componentId } = useComponentId(componentName, accessibilityLabel);

  const showBaseLineDebug = context?.features?.showBaseLineDebug ?? false;

  let backgroundColor = value ? Colors.green_03 : Colors.black_07;
  if (disabled) {
    backgroundColor = value ? Colors.green_09 : Colors.black_05;
  }

  return (
    <ComponentContext.Provider
      value={{
        componentName,
        params,
        state: disabled ? 'disabled' : 'enabled',
        action: 'click',
      }}
    >
      <TouchableOpacity
        {...props}
        disabled={disabled}
        accessibilityState={{
          checked: value,
          disabled: disabled === null ? false : disabled,
          ...props.accessibilityState,
        }}
        accessibilityLabel={componentId}
        onPress={() => onChange?.(!value)}
        style={[
          style,
          styles.container,
          { backgroundColor, alignItems: circleAlign },
          showBaseLineDebug && styles.debugBaseLine,
        ]}
      >
        <View
          style={[styles.circle, { backgroundColor: circleBackgroundColor }]}
        >
          <View style={[styles.circleSmall, { backgroundColor }]} />
        </View>
      </TouchableOpacity>
    </ComponentContext.Provider>
  );
};

export { Switch };
