import * as React from 'react';
import { TouchableOpacity } from 'react-native';

import { Text } from '../../components/text';
import { enhanceTextStyle, enhanceViewStyle } from '../../utils/styles';

import { viewPresets, captionPresets } from './button.presets';
import { ButtonProps as Props } from './button.props';

/**
 * Display a button that can be customized.
 * This component is a HOC over the built-in React Native one.
 *
 * @param text An optional text to display if not using `tx` or nested components.
 * @param tx An optional ext which is looked up via i18n.
 * @param txOptions Optional options to pass to i18n.
 * @param full The button uses 100% width
 * @param style An optional style override useful for padding & margin.
 * @param textStyle An optional style override useful for the button text.
 * @param preset One of the different types of text presets.
 * @param children One of the different types of text presets.
 */
export const Button: React.FC<Props> = (props) => {
  const {
    disabled,
    preset,
    text,
    textTransform,
    tx,
    txOptions,
    full,
    style: styleOverride,
    textStyle: textStyleOverride,
    children,
    ...rest
  } = props;
  const opacity = { opacity: disabled ? 0.55 : 1 };
  const fullWidth = { width: full ? '100%' : 'auto' };
  const viewStyle = enhanceViewStyle([
    viewPresets[preset] || viewPresets.primary,
    styleOverride,
    opacity,
    fullWidth,
  ]);
  const textStyle = enhanceTextStyle([
    captionPresets[preset] || captionPresets.primary,
    textStyleOverride,
    opacity,
  ]);
  const content = children || (
    <Text style={textStyle} text={text} transform={textTransform} tx={tx} txOptions={txOptions} />
  );

  return (
    <TouchableOpacity {...{ disabled }} style={viewStyle} {...rest}>
      {content}
    </TouchableOpacity>
  );
};

Button.defaultProps = {
  full: false,
  preset: 'primary',
};
