import React from 'react';
import { clsx } from 'clsx';

import { Box } from '../box';
import { forwardRef } from '../utils/react';
import * as css from './text.css';

/*-- Types --*/

export type Variant = css.TextVariant;

export interface TextProps extends css.TextVariants {
  /** Defines HTML tag or component for certain variants (e.g. { h1: 'div' }). */
  variantMapping?: {
    [K in Variant]?: React.ElementType;
  };
}

/*-- Main --*/

const defaultVariantMapping: TextProps['variantMapping'] = {
  h1: 'h1',
  h2: 'h2',
  h3: 'h3',
  h4: 'h4',
  h5: 'h5',
  h6: 'h6',
  body1: 'p',
  body2: 'p',
};

export const Text = forwardRef<'span', TextProps>(function Text(
  {
    as,
    align,
    className,
    variant = 'body1',
    variantMapping = {},
    size,
    weight,
    color,
    noWrap,
    ...rest
  },
  ref,
) {
  const component =
    as ||
    (typeof variant === 'string' && variantMapping[variant]) ||
    defaultVariantMapping[variant] ||
    'span';

  const cn = clsx(
    className,
    css.text({ align, variant, size, weight, color, noWrap }),
  );

  return <Box ref={ref} as={component} className={cn} {...rest} />;
});
