import React, { FC, useContext } from 'react';
import { TouchableOpacity, View } from 'react-native';

import { RadioProps } from './types';
import { Text } from '../Text';
import styles from './styles';
import { useComponentId } from '../Application';
import {
  ApplicationContext,
  ComponentContext,
  MiniAppContext,
} from '../Context';
import { Spacing } from '../Consts';

const Radio: FC<RadioProps> = ({
  value,
  groupValue,
  disabled = false,
  onChange,
  label,
  style,
  params,
  accessibilityState,
  accessibilityLabel,
  ...props
}) => {
  const { theme } = useContext(ApplicationContext);
  const context = useContext<any>(MiniAppContext);
  const selected = value === groupValue;
  const componentName = 'Radio';
  const { componentId } = useComponentId(
    `${componentName}${label ? `/${label}` : ''}`,
    accessibilityLabel,
  );

  const showBaseLineDebug = context?.features?.showBaseLineDebug ?? false;
  let disabledStyle = {};
  let checkBoxStyle = {
    borderWidth: 2,
    borderColor: theme.colors.text.default,
  };

  if (selected) {
    checkBoxStyle = {
      borderWidth: 6,
      borderColor: theme.colors.primary,
    };
  }
  if (disabled) {
    disabledStyle = {
      borderColor: selected
        ? theme.colors.background.tonal
        : theme.colors.text.disable,
    };
  }

  return (
    <ComponentContext.Provider
      value={{
        componentName,
        componentId,
        params,
        state: disabled ? 'disabled' : 'enabled',
        action: 'click',
      }}
    >
      <TouchableOpacity
        {...props}
        disabled={disabled}
        onPress={onChange}
        style={[
          style,
          {
            flexDirection: 'row',
            alignItems: 'center',
          },
          showBaseLineDebug && styles.debugBaseLine,
        ]}
        accessibilityState={{
          checked: selected,
          disabled: disabled as boolean,
          ...accessibilityState,
        }}
        accessibilityLabel={componentId}
      >
        <View
          style={[
            styles.radio,
            checkBoxStyle,
            disabledStyle,
            { marginRight: label ? Spacing.S : 0 },
          ]}
        />
        {!!label && (
          <Text
            typography={'body_default_regular'}
            style={styles.radioText}
            accessibilityLabel={componentId + '|text'}
          >
            {label}
          </Text>
        )}
      </TouchableOpacity>
    </ComponentContext.Provider>
  );
};

export { Radio };
