import React, { useState, useEffect } from 'react';
import { Button } from '@easyv/antd';
import QuestionCircleOutlined from '@ant-design/icons/QuestionCircleOutlined';
import { Drawer, EasyRadio, Switch, Tooltip } from '@easyv/react-gui';
import ConditionItem from './ConditionItem';
import { generateId } from 'utils/utils';
import styles from './ConditionEdit.less';
import DataTooltipPopover from './DataTooltipPopover';
import { CloseOutlined } from '@easyv/react-icons';
import message from 'components/message';

const conditionOptions = [
  { name: '满足全部条件', value: 'all' },
  { name: '满足任意条件', value: 'one' }
];

export default function ConditionEdit({
  visible,
  eventIndex,
  conditionId,
  type = 'all',
  reverse = true,
  value = [],
  tooltipData,
  onClose,
  onChange
}: {
  visible: boolean;
  eventIndex?: number;
  conditionId?: number;
  type: string;
  value: any;
  reverse?: boolean;
  tooltipData?: {
    type: string;
    data: any;
    fields: any;
  };
  onClose: () => any;
  onChange: (param) => any;
}) {
  const [adding, setAdding] = useState(false);

  useEffect(() => {
    if (visible) {
      if (value.length === 0) {
        setAdding(true);
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible]);

  const handleTypeChange = (value) => {
    onChange({ value, key: 'conditionType', paths: [eventIndex] });
  };

  const handleAddClick = () => {
    if (adding) {
      message.error('当前有未编辑完的条件');
    } else {
      setAdding(true);
    }
  };

  const handleCancel = () => {
    setAdding(false);
  };

  const handleConditionAdd = async (params) => {
    const newKey = `condition_${generateId()}`;
    const result = await onChange({ value: { ...params, id: newKey }, paths: [eventIndex, 'conditions'], key: value.length });
    if (result) {
      setAdding(false);
    }
  };

  const handleConditionUpdate = (params) => {
    const conditionIndex = value.findIndex((d) => d.id === params.id);
    return onChange({ value: params, paths: [eventIndex, 'conditions'], key: conditionIndex });
  };

  const handleConditionDelete = async (conditionId) => {
    const conditionIndex = value.findIndex((d) => d.id === conditionId);
    const result = await onChange({ paths: [eventIndex, 'conditions'], key: conditionIndex });
    return result;
  };

  const handleReverseChange = (checked) => {
    onChange({ paths: [eventIndex], key: 'reverse', value: checked });
  };
  const title = (
    <div className={styles.title}>
      <span>自定义条件编辑</span>
      <CloseOutlined
        onClick={() => {
          onClose?.();
        }}
        className={styles.icon}
      />
    </div>
  );
  return (
    <Drawer
      className={`${styles.drawer} ${styles.filter} ${styles.drawerTitle}`}
      title={title}
      placement="right"
      closable={false}
      onClose={onClose}
      visible={visible}>
      <div style={{ paddingLeft: 16, paddingRight: 16 }}>
        <div className={styles.container}>
          <label className={styles.label}>判断类型</label>
          <div className={styles.field}>
            <EasyRadio options={conditionOptions} onChange={handleTypeChange} value={type} />
          </div>
        </div>
      </div>

      <div style={{ marginTop: 12, paddingLeft: 16, paddingRight: 16, marginBottom: 20 }}>
        <Button type="primary" ghost style={{ width: '100%' }} onClick={handleAddClick}>
          + 添加条件
        </Button>
      </div>

      <div style={{ paddingBottom: 48 }}>
        {value.map((d: any) => (
          <ConditionItem
            defaultCollapsed={conditionId !== d.id}
            key={d.id}
            value={d}
            onCancel={handleCancel}
            onSubmit={handleConditionUpdate}
            onDelete={handleConditionDelete}
          />
        ))}

        {adding && <ConditionItem onCancel={handleCancel} onSubmit={handleConditionAdd} onDelete={handleCancel} />}
      </div>

      <div className={styles.mode}>
        {tooltipData?.type && (
          <DataTooltipPopover type={tooltipData.type} data={tooltipData.data} fields={tooltipData.fields}>
            <div className={styles.dataTip}>查看条件数据参数提示</div>
          </DataTooltipPopover>
        )}
        <div>
          <label className={styles.label}>
            <span>自动模式</span>
            <Tooltip title="当不满足条件时重置动作">
              <QuestionCircleOutlined className="whiteHover" style={{ cursor: 'pointer', marginLeft: 4 }} />
            </Tooltip>
          </label>

          <Switch size="small" checked={reverse} onChange={handleReverseChange} />
        </div>
      </div>
    </Drawer>
  );
}
