import { getClassNames } from '@websolutespa/bom-core';
import { FormState } from '@websolutespa/bom-mixer-forms';
import { forwardRef } from 'react';
import styled from 'styled-components';
import { UIComponentWithRef, UIStyledComponentProps } from '../../components/types';
import { getCssResponsive } from '../../components/utils';
import { getVariant, useVariants } from '../../variants';
import { IFieldVariants, fieldVariants } from './field.variants';

type Props = {
  state?: FormState<any>;
  variant?: keyof typeof fieldVariants | (string & {});
  variants?: IFieldVariants;
};

export type FieldProps = UIStyledComponentProps<Props>;

export type FieldComponent<C extends React.ElementType = 'div'> = UIComponentWithRef<C, Props>;

const StyledField = styled.div<FieldProps>`
  ${props => getVariant(props.variant, props.variants)}
  ${props => getCssResponsive(props)}
`;

export const Field: FieldComponent = forwardRef<HTMLDivElement, FieldProps>(({
  className,
  state,
  variant = 'default',
  variants,
  ...props
}, ref) => {
  const classNames = getClassNames('field', className, variant, state?.flags);
  const globalVariants = useVariants('field', fieldVariants);
  variants = variants || globalVariants;
  return (
    <StyledField ref={ref} className={classNames} as="div" variant={variant} variants={variants} {...props} />
  );
});

Field.displayName = 'Field';
