import * as React from 'react';
import * as PropTypes from 'prop-types';

import classNames from '../../../utils/classnames';
import getLocalCounter from '../../../utils/getLocalCounter';
import FormCell from '../formcell';
import { usePlatform } from '../../../utils/platform';
import { Switch as TeaSwitch } from 'tea-component';
export default function Switch({
  // 系统属性
  id,
  className,
  style,
  events,
  // 组件属性
  label,
  labelVisible,
  checked: defaultChecked,
  layout,
  disabled,
  requiredFlag,
}) {
  const isFlex = layout !== 'vertical';
  const cls = classNames({
    'weda-ui': true,
    'weda-switch': true,
    [className]: className,
  });
  const subCls = classNames({
    'weui-cell': true,
    'weui-cell_active': true,
    'weui-cell_switch': true,
    'weui-flex__item': isFlex,
    'weui-cell_disabled': disabled,
  });

  const platform = usePlatform();
  const [checked, setChecked] = React.useState(defaultChecked);
  // 两次默认值不同时, 需要刷新
  const prevDefaultCheckedRef = React.useRef();
  React.useEffect(() => {
    if (prevDefaultCheckedRef.current !== defaultChecked) {
      prevDefaultCheckedRef.current = defaultChecked;
      setChecked(defaultChecked);
    }
  });

  const onChange = function (e) {
    setChecked(e.target.checked);
    events.change({ value: e.target.checked }, { originEvent: e });
  };

  // 现在低码组件往源码组件传入的id不唯一, 暂时使用hashcode替代
  const hashcode = getLocalCounter();
  const _id = `switch-${hashcode}`;
  const switchElement =
    platform === 'h5' ? (
      <div className={subCls}>
        {isFlex ? <div className="weui-cell__bd"></div> : null}
        <div className={isFlex ? 'weui-cell__ft' : 'weui-cell__bd'}>
          <label htmlFor={_id} key={_id} className="weui-switch-cp">
            <input
              id={_id}
              className="weui-switch-cp__input"
              type="checkbox"
              checked={checked}
              disabled={disabled}
              onChange={onChange}
            />
            <div className="weui-switch-cp__box"></div>
          </label>
        </div>
      </div>
    ) : (
      <TeaSwitch id={_id} disabled={disabled} onChange={onChange} />
    );
  return (
    <FormCell
      id={id}
      className={cls}
      style={style}
      label={labelVisible ? label : null}
      layout={layout}
      multiCell={true}
      requiredFlag={requiredFlag}
    >
      {switchElement}
    </FormCell>
  );
}
