import * as React from 'react';
import * as PropTypes from 'prop-types';
import { ConfigProvider, Radio as TeaRadio } from 'tea-component';

import { usePlatform } from '../../../utils/platform';
import classNames from '../../../utils/classnames';
import getLocalCounter from '../../../utils/getLocalCounter';
import isObjectEqual from '../../../utils/isObjectEqual';
import FormCell from '../formcell';

import './index.css';
export default function Radio({
  // 系统属性
  id,
  className,
  style,
  events,
  // 组件属性
  label,
  labelVisible,
  name,
  range,
  layout,
  disabled,
  requiredFlag,
}) {
  const platform = usePlatform();
  const isH5 = platform === 'h5';
  const cls = classNames({
    'weda-ui': true,
    'weda-radio': true,
    [className]: className,
  });
  const subCls = classNames({
    'weui-cell': isH5,
    'weui-cell_active': isH5,
    'weui-check__label': isH5,
    'weui-cell_disabled': isH5 && disabled,
  });

  const [checkedItemValue, setCheckedItemValue] = React.useState(
    range.find((item) => item.checked)?.value
  );
  // 两次range不同时, 需要刷新checkedItemValue
  const prevRangeRef = React.useRef();
  React.useEffect(() => {
    if (!isObjectEqual(prevRangeRef.current, range)) {
      prevRangeRef.current = range;
      setCheckedItemValue(range.find((item) => item.checked)?.value);
    }
  });

  /**
   * 在ios h5端, label和input的绑定不生效
   * 导致 onChange 事件触发有问题, 所以改为监听 onClick 事件
   */
  const getChangeHandler = function (value) {
    const onChange = function (e) {
      setCheckedItemValue(value);
      events.change({ value }, { originEvent: e });
    };
    return onChange;
  };

  // 现在低码组件往源码组件传入的id不唯一, 暂时使用hashcode替代
  const hashcode = getLocalCounter();
  let radioElement;
  if (isH5) {
    radioElement = range.map(({ label, value }, index) => {
      const _id = `radio-${hashcode}-${index}`;
      const _name = `radio-${hashcode}-${name}`;
      return (
        <label
          className={subCls}
          htmlFor={_id}
          key={_id}
          onClick={getChangeHandler(value)}
        >
          <div className="weui-cell__hd">
            <input
              type="radio"
              className="weui-check"
              value={value}
              name={_name}
              id={_id}
              checked={checkedItemValue === value}
              disabled={disabled}
              onClick={(e) => e.stopPropagation()}
            />
            <i className="weui-icon-checked"></i>
          </div>
          <div className="weui-cell__bd">
            <p>{label}</p>
          </div>
        </label>
      );
    });
  } else {
    // pc
    radioElement = (
      <ConfigProvider classPrefix="wedatea2td">
        <TeaRadio.Group
          disabled={disabled}
          value={checkedItemValue}
          onChange={(value) => getChangeHandler(value)()}
        >
          {range.map(({ value, label }, index) => {
            const _id = `radio-${hashcode}-${index}`;
            return (
              <TeaRadio key={_id} name={value} id={_id}>
                {label}
              </TeaRadio>
            );
          })}
        </TeaRadio.Group>
      </ConfigProvider>
    );
  }
  return (
    <FormCell
      id={id}
      className={cls}
      style={style}
      label={labelVisible ? label : null}
      layout={layout}
      multiCell={true}
      requiredFlag={requiredFlag}
    >
      {radioElement}
    </FormCell>
  );
}
