import { getClassNames } from '@websolutespa/bom-core';
import { forwardRef } from 'react';
import styled from 'styled-components';
import { Text } from '../../components';
import { UIComponentWithRef, UIStyledComponentProps } from '../../components/types';
import { getCssResponsive } from '../../components/utils';
import { getVariant, useVariants } from '../../variants';
import { IFormErrorVariants, formErrorVariants } from './form-error.variants';

type Props = {
  error?: Error;
  variant?: keyof typeof formErrorVariants | (string & {});
  variants?: IFormErrorVariants;
};

export type FormErrorProps = UIStyledComponentProps<Props, 'form'>;

export type FormErrorComponent<C extends React.ElementType = 'form'> = UIComponentWithRef<C, Props>;

const StyledFormError = styled(Text)`
  ${props => getVariant(props.variant, props.variants)}
  ${props => getCssResponsive(props)}
`;

export const FormError: FormErrorComponent = forwardRef(({
  className,
  variant = 'default',
  variants,
  ...props
}, ref) => {
  const classNames = getClassNames('form-error', className, variant);
  const globalVariants = useVariants('formError', formErrorVariants);
  variants = variants || globalVariants;
  return (
    <StyledFormError ref={ref} className={classNames} variant={variant} variants={variants} {...props} />
  );
});

FormError.displayName = 'FormError';
