import { createElement, useState, memo } from '__RAX_OR_REACT__';
import { string, func, arrayOf, shape, object, bool } from 'prop-types';
import * as types from './prop-types';
import { toArray } from '../../../share/utils';
import { $emit } from '../../common/event';
import RadioGroup from './RadioGroup';
import Block from './Block';

function CompGroups(props) {
  let refEl = null;
  const {
    name,
    title,
    radioProps = [],
    blocks,
    render,
    isInverse,
    theme,
  } = props;

  const defaultOptions = {};
  radioProps.forEach(({ name, defaultValue, options }) => {
    defaultOptions[name] =
      defaultValue !== undefined
        ? defaultValue
        : options[0] && options[0].value;
  });

  const [options, setOptions] = useState(defaultOptions);

  function handleChange(name, value) {
    setOptions({
      ...options,
      [name]: value,
    });

    // 触发重新配置事件
    setTimeout(() => {
      refEl && $emit(refEl, 'reconfig');
    });
  }

  function refFn(el) {
    !refEl && (refEl = el);
  }

  return (
    <div
      key={name}
      className={'comp-groups' + (isInverse ? ' inverse' : '')}
      ref={refFn}
    >
      <div className='headline2'>{title}</div>
      {radioProps.map(prop => (
        <RadioGroup
          key={prop.name}
          defaultValue={options[prop.name]}
          {...prop}
          onChange={handleChange}
        />
      ))}

      {toArray(blocks).map((prop, index) => (
        <Block
          key={index}
          render={render}
          {...prop}
          theme={theme}
          groupOption={{ ...options, groupName: name }}
        />
      ))}
    </div>
  );
}

CompGroups.propTypes = {
  name: string,
  title: string,
  isInverse: bool,
  radioProps: types.Props,
  blocks: arrayOf(
    shape({
      name: string,
    })
  ),
  render: func,
  theme: arrayOf(object),
  isDevice: bool,
};

export default memo(CompGroups);
