import React, { forwardRef, useMemo } from "react";
import { Text as RNText, TextProps } from "react-native";

import theme from "mazlo-theme";

import styledComponent from "../../utils/styledComponent";
import styles from "./styles";

export type Props = {
  as?: string;
  bold?: boolean;
  children?: React.ReactNode;
  h1?: boolean;
  h2?: boolean;
  h3?: boolean;
  h4?: boolean;
  inherit?: boolean;
  italic?: boolean;
  size?: string;
  variant?: string;
  flex?: number | true;
} & TextProps;

const StyledText = styledComponent<TextProps>(RNText);

const Text = forwardRef<typeof StyledText, Props>(
  (
    {
      as,
      style = null,
      bold,
      h1,
      h2,
      h3,
      h4,
      inherit,
      italic,
      size,
      variant,
      flex,
      ...props
    }: Props,
    forwardedRef
  ) => {
    const textStyle = useMemo(
      () => [
        flex != null && {
          flex: flex === true ? 1 : flex,
        },
        !inherit && styles.body,
        as && theme.styles[as],
        variant && theme.variants.text[variant],
        bold && theme.styles.strong,
        italic && theme.styles.em,
        (h1 || h2 || h3 || h4) && styles.heading,
        h1 && theme.styles.h1,
        h2 && theme.styles.h2,
        h3 && theme.styles.h3,
        h4 && theme.styles.h4,
        size && { fontSize: theme.fontSizes[size] },
        ...[].concat(style),
      ],
      [flex, inherit, as, variant, bold, italic, h1, h2, h3, h4, size, style]
    );

    return <StyledText ref={forwardedRef} style={textStyle} {...props} />;
  }
);

Text.displayName = "Text";

export default Text;
