import React, { useEffect, useState } from 'react';
import { View, Image, Text } from '@tarojs/components';
import classNames from 'classnames';
const checkImg = 'https://wanmi-b2b-x-site.oss-cn-shanghai.aliyuncs.com/pandora-ui/assets/components/images/checkbox/icon-check.png';
const uncheckImg = 'https://wanmi-b2b-x-site.oss-cn-shanghai.aliyuncs.com/pandora-ui/assets/components/images/checkbox/icon-uncheck.png';
const disabledImg = 'https://wanmi-b2b-x-site.oss-cn-shanghai.aliyuncs.com/pandora-ui/assets/components/images/checkbox/icon-disabled.png';

interface IWMCheckboxProps {
  /** 是否选中 */
  checked?: boolean;
  /** 是否禁用 */
  disabled?: boolean;
  /** 标签 */
  label?: string;
  /** 点击回调 */
  onClick: (checked: boolean) => void;
}

/**
 * 多选框组件
 */
const Checkbox: React.FC<IWMCheckboxProps> = ({
  checked = false,
  disabled = false,
  label = '',
  onClick = (_checked: boolean) => {},
}) => {
  const [currentChecked, setCurrentChecked] = useState(checked);

  /* eslint-disable */
  useEffect(() => {
    if (currentChecked !== checked) {
      setCurrentChecked(checked);
    }
  }, [checked]);
  /* eslint-enable */

  const handleClick = () => {
    if (!onClick) {
      return;
    }
    if (disabled) {
      onClick(currentChecked);
      return;
    }
    const tmpChecked = !currentChecked;
    setCurrentChecked(tmpChecked);
    onClick(tmpChecked);
  };

  const imgStyle = classNames(
    'img',
    disabled && (currentChecked ? 'disabled-img' : 'disabled-unchecked-img'),
  );
  const labelStyle = classNames('label', disabled && 'disabled-label');
  return (
    <View
      className='wm-check'
      onClick={(e) => {
        e.stopPropagation();
        handleClick();
      }}>
      <View className='img-box'>
        <Image
          className={imgStyle}
          src={currentChecked ? checkImg : disabled ? disabledImg : uncheckImg}
        />
      </View>
      {!!label && <Text className={labelStyle}>{label}</Text>}
    </View>
  );
};

export default Checkbox;
