import React, { FC, useContext } from 'react';
import { TouchableOpacity, View } from 'react-native';
import { CheckBoxProps } from './types';
import styles from './styles';
import { useComponentId } from '../Application';
import {
  ApplicationContext,
  ComponentContext,
  MiniAppContext,
} from '../Context';
import { Text } from '../Text';
import { Icon } from '../Icon';

const CheckBox: FC<CheckBoxProps> = ({
  value,
  disabled = false,
  onChange,
  style,
  label,
  indeterminate,
  params,
  accessibilityState,
  ...props
}) => {
  const { theme } = useContext(ApplicationContext);
  const context = useContext<any>(MiniAppContext);
  const haveValue = value || indeterminate;
  const iconSource = indeterminate ? 'ic_minus' : 'ic_checked';
  let borderColor = theme.colors.text.default;
  let backgroundColor = 'transparent';
  const componentName = 'CheckBox';
  const { componentId } = useComponentId(
    `${componentName}${label ? `/${label}` : ''}`,
    props.accessibilityLabel,
  );

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

  if (haveValue) {
    borderColor = theme.colors.primary;
    backgroundColor = theme.colors.primary;
  }

  if (disabled) {
    borderColor = theme.colors.border.disable;
    backgroundColor = 'transparent';
    if (haveValue) {
      borderColor = theme.colors.background.tonal;
      backgroundColor = theme.colors.background.tonal;
    }
  }

  return (
    <ComponentContext.Provider
      value={{
        componentName,
        componentId,
        params,
        state: disabled ? 'disabled' : 'filled',
        action: 'click',
      }}
    >
      <TouchableOpacity
        {...props}
        accessibilityLabel={componentId}
        activeOpacity={0.8}
        onPress={() => onChange?.(!value)}
        disabled={disabled}
        accessibilityState={{
          checked: haveValue,
          disabled,
          ...accessibilityState,
        }}
        style={[
          style,
          styles.container,
          showBaseLineDebug && styles.debugBaseLine,
        ]}
      >
        <View
          style={[
            { borderColor, backgroundColor, borderWidth: 1 },
            styles.checkbox,
          ]}
        >
          {haveValue && (
            <Icon
              color={theme.colors.background.surface}
              size={20}
              source={iconSource}
            />
          )}
        </View>
        {!!label && (
          <Text typography={'body_default_regular'} style={styles.label}>
            {label}
          </Text>
        )}
      </TouchableOpacity>
    </ComponentContext.Provider>
  );
};

export { CheckBox };
