import { createElement, forwardRef, HTMLAttributes, RefForwardingComponent } from 'rax';
import { StyledComponentProps, useStyles } from '@rax-ui/styles';
import Context, { FormContextProps } from './context';
import View from 'rax-view';
import StyleProvider from './style';

export interface FormProps extends HTMLAttributes<HTMLElement>, StyledComponentProps<any> {
  align: 'left' | 'right';
  labelType: 'inner' | 'upper';
  labelWidth: string | number;
}

const Form: RefForwardingComponent<any, FormProps> = (props, ref) => {
  const { children, align, labelType = 'upper', labelWidth, style, ...others } = props;
  const styles = useStyles(StyleProvider, others, (classNames) => {
    return {
      form: classNames('form'),
      subHeader: classNames('form__sub-header'),
      footer: classNames('form__footer'),
      content: classNames('form__content'),
      item: classNames('form__item'),
      itemContainer: classNames('form__item-container'),
      itemLabelContainer: classNames('form__item-label-container'),
      itemLabelInnerContainer: classNames('form__item-label-inner-container'),
      itemLabel: classNames('form__item-label'),
      itemInnerContainer: classNames('form--inner__item-container'),
      itemInnerLabel: classNames('form--inner__item-label'),
      itemInput: classNames('form__item-input'),
      itemHelp: classNames('form__item-help'),
      itemHelpText: classNames('form__item-help-text'),
      itemErrorText: classNames('form__item-error-text'),
      itemRequiredText: classNames('form__item-required-text'),
      itemInnerRequiredText: classNames('form__item-required-text__inner'),
    };
  });

  return (
    <Context.Provider value={{ styles, labelType, labelWidth } as FormContextProps}>
      <View {...others} style={{ ...styles.form, ...style }} ref={ref}>
        {children}
      </View>
    </Context.Provider>
  );
};

export default forwardRef<any, FormProps>(Form);
