import React, {useMemo} from 'react';
import {
  Text as RNText,
  TextProps as RNTextProps,
  TextStyle,
} from 'react-native';
import {useTheme} from '@shared/theme';
import {FONT_SCALE} from '@shared/constants';
import {getCommunityFeature} from '@stores/communityFeatures';

import {getTextStyles} from './utils';
import {TypographyVariant, WeightValues} from './interfaces';
import {TYPOGRAPHY_STYLES} from './styles';

export interface TypographyProps extends RNTextProps {
  variant?: TypographyVariant;
  weight?: WeightValues;
  color?: string;
  align?: TextStyle['textAlign'];
  fontStyle?: TextStyle['fontStyle'];
}

export function Typography({
  style,
  children,
  color,
  weight = 'regular',
  align = 'left',
  maxFontSizeMultiplier = FONT_SCALE,
  variant = 's',
  fontStyle = 'normal',
  ...props
}: TypographyProps) {
  const {theme} = useTheme();
  const preventCopy = getCommunityFeature('PREVENT_COPY_TO_CLIPBOARD');
  const selectableOverride = preventCopy ? {selectable: false} : {};

  // Memorize these styles for the internal use of StyleSheet.flatten
  const styles = useMemo(() => {
    return [
      {
        color: color || theme.text.neutral.default,
        textAlign: align,
      },
      TYPOGRAPHY_STYLES[variant],
      getTextStyles({
        style,
        fontStyle,
        weight,
      }),
    ];
  }, [
    color,
    theme.text.neutral.default,
    align,
    variant,
    style,
    fontStyle,
    weight,
  ]);

  return (
    <RNText
      style={styles}
      maxFontSizeMultiplier={maxFontSizeMultiplier}
      minimumFontScale={1}
      allowFontScaling={true}
      {...props}
      {...selectableOverride}>
      {children}
    </RNText>
  );
}

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