import React from 'react';
import AntdForm from 'antd/es/form';
import { FormContext } from 'antd/es/form/context';
import classnames from 'classnames';

import { ConfigContext } from '../config-provider';
import './index.less';

const Form = props => {
  const { getPrefixCls } = React.useContext(ConfigContext);
  const {
    prefixCls: customizePrefixCls,
    labelCol,
    wrapperCol,
    ...restProps
  } = props;
  const prefixCls = getPrefixCls('form', customizePrefixCls);
  return (
    <AntdForm
      prefixCls={prefixCls}
      labelCol={{ prefixCls: 'baas-col' }}
      labelCol={labelCol}
      wrapperCol={wrapperCol}
      {...restProps}
    />
  );
};

const FormItem = props => {
  const { getPrefixCls, antPrefix } = React.useContext(ConfigContext);
  const {
    className,
    prefixCls: customizePrefixCls,
    labelCol,
    wrapperCol,
    ...restProps
  } = props;
  const prefixCls = getPrefixCls('form', customizePrefixCls);
  return (
    <FormContext.Consumer>
      {({
        labelCol: contextLablelCol,
        wrapperCol: contextWrapperCol,
        ...rest
      }) => {
        const mergedLabelCol = labelCol || contextLablelCol || {};
        const mergedWrapperCol = wrapperCol || contextWrapperCol || {};
        return (
          <AntdForm.Item
            prefixCls={prefixCls}
            labelCol={{ prefixCls: `${antPrefix}-col`, ...mergedLabelCol }}
            wrapperCol={{ prefixCls: `${antPrefix}-col`, ...mergedWrapperCol }}
            {...restProps}
            className={classnames(`${antPrefix}-row`, className)}
          />
        );
      }}
    </FormContext.Consumer>
  );
};

const FormList = props => {
  const { getPrefixCls } = React.useContext(ConfigContext);
  const { prefixCls: customizePrefixCls, ...restProps } = props;
  const prefixCls = getPrefixCls('form', customizePrefixCls);
  return <AntdForm.List prefixCls={prefixCls} {...restProps} />;
};

const FormProvider = props => <AntdForm.FormProvider {...props} />;

Form.Item = FormItem;
Form.List = FormList;
Form.Provider = FormProvider;

export default Form;
