import { getClassNames } from '@websolutespa/bom-core';
import { FormState, FormValidationError } from '@websolutespa/bom-mixer-forms';
import { useLabel } from '@websolutespa/bom-mixer-hooks';
import styled from 'styled-components';
import { UIStyledComponentProps } from '../components/types';
import { getCssResponsive } from '../components/utils';
import { getVariant, useVariants } from '../variants';
import { IFieldErrorVariants, fieldErrorVariants } from './field-error.variants';

type Props = {
  state: FormState<any>;
  label?: string;
  className?: string;
  variant?: keyof typeof fieldErrorVariants | (string & {});
  variants?: IFieldErrorVariants;
};

export type FieldErrorProps = UIStyledComponentProps<Props>;

const StyledFieldError = styled.div<Omit<FieldErrorProps, 'state'>>`
  ${props => getVariant(props.variant, props.variants)}
  ${props => getCssResponsive(props)}
`;

export function FieldError({
  state,
  label,
  className,
  variant = 'default',
  variants,
  ...props
}: FieldErrorProps) {
  const errorLabel = useLabel();
  const getErrorLabel = (error: FormValidationError) => {
    const keyLabel = `error.${error.key}.label`;
    const key = `error.${error.key}`;
    const errorKeyLabel = label && errorLabel(keyLabel, { label });
    const errorKey = label ?
      (errorKeyLabel !== keyLabel ? errorKeyLabel : errorLabel(key, { label })) :
      errorLabel(key);
    return errorKey;
  };
  const classNames = getClassNames('field-error', className, variant);
  const globalVariants = useVariants('fieldError', fieldErrorVariants);
  variants = variants || globalVariants;
  return (
    <>
      {state.flags.touched && state.errors.map(error => (
        <StyledFieldError className={classNames} key={error.key} variant={variant} variants={variants} role="alert" {...props}>{getErrorLabel(error)}</StyledFieldError>
      ))}
    </>
  );
}

