import React, {ForwardedRef, forwardRef, useMemo} from 'react';
import {
  Text as RNText,
  TextProps as RNTextProps,
  TextStyle,
} from 'react-native';
import {useTheme} from '@shared/theme';

import {LEGACY_VARIANT_WEIGHT, TextVariantStyles} from './styles';
import {TextVariant, TextWeight} from './interfaces';
import {getTextStyles} from './utils';

const MAX_FONT_SIZE_MULTIPLIER = 1.18;

export interface TextProps extends RNTextProps {
  variant?: TextVariant;
  weight?: keyof typeof TextWeight;
  color?: string | false;
  align?: 'auto' | 'left' | 'right' | 'center' | 'justify';
  fontStyle?: TextStyle['fontStyle'];
}

/**
 * @deprecated Use `_core/Typography` instead
 */
function Text(
  {
    style,
    children,
    color,
    weight,
    minimumFontScale = 1,
    align = 'left',
    maxFontSizeMultiplier = MAX_FONT_SIZE_MULTIPLIER,
    variant = 'body1',
    fontStyle = 'normal',
    ...props
  }: TextProps,
  ref: ForwardedRef<RNText>,
) {
  const {theme} = useTheme();
  // Memorize these styles for the internal use of StyleSheet.flatten
  const styles = useMemo(() => {
    return [
      {
        color: color || theme.text.neutral.default,
        textAlign: align,
      },
      TextVariantStyles[variant],
      getTextStyles({
        style,
        fontStyle,
        weight: weight || LEGACY_VARIANT_WEIGHT[variant] || 'regular',
      }),
    ];
  }, [
    color,
    theme.text.neutral.default,
    align,
    variant,
    style,
    fontStyle,
    weight,
  ]);

  return (
    <RNText
      ref={ref}
      style={styles}
      maxFontSizeMultiplier={maxFontSizeMultiplier}
      minimumFontScale={minimumFontScale}
      {...props}>
      {children}
    </RNText>
  );
}

export * from './interfaces';
export * from './utils';

/**
 * @deprecated Use `_core/Typography` instead
 */
export default forwardRef(Text);
