import React, { useState, useCallback } from 'react';
import { useDispatch } from 'react-redux';
import EasyvButton from 'components/EasyvButton';
import { Input, Drawer } from '@easyv/react-gui';
import FilterAdd from './Add';
import FilterList from './List';
import SelectFilterList from './SelectList';
import { addFilter } from 'models/filter';
import styles from '../index.less';
import classNames from 'classnames';
import { deleteFilter } from 'models/filter';
import EasyvModal, { useConfirmRef } from 'components/EasyvModal';
import { CloseOutlined, PlusOutlined } from '@easyv/react-icons';

const { Search } = Input;

function Filter({ visible, onClose }) {
  const dispatch = useDispatch();
  const [adding, setAdding] = useState(false);
  const [value, setValue] = useState('');
  const [edit, setEdit] = useState(false);
  const [selectFilterList, setSelectFilterList] = useState([]);
  const [filtersWithComponents, setFiltersWithComponents] = useState([]);
  const deleteRef = useConfirmRef();
  const title = (
    <div className={styles.title}>
      <span>项目过滤器</span>
      <CloseOutlined
        onClick={() => {
          setEdit(false);
          setSelectFilterList([]);
          onClose?.();
        }}
        className={styles.icon}
      />
    </div>
  );
  const handleAdd = useCallback(async (value) => {
    const result = await dispatch(addFilter(value));
    if (result) {
      setAdding(false);
    }
  }, []);

  const handleRemove = useCallback(() => {
    setAdding(false);
  }, []);

  const onInputChange = (e) => {
    const value = e.target.value.trim();
    setValue(value);
  };

  const onDeleteFilter = async () => {
    const _usedComponents = filtersWithComponents
      .filter((d) => selectFilterList.includes(d.id))
      .filter((d) => d.usedComponents)
      .map((d) => d.usedComponents);

    const usedComponents = _usedComponents.map((d) => {
      return d.map((v) => {
        return v.id;
      });
    });

    const components = new Set(usedComponents.flat(1));

    const result = await dispatch(
      deleteFilter({
        ids: selectFilterList,
        components: [...components],
      }),
    );

    if (result) {
      setEdit(false);
      setSelectFilterList([]);
    }
  };

  return (
    <Drawer
      className={classNames(styles.drawer, styles.filter, styles.drawerTitle)}
      closable={false}
      title={title}
      placement="right"
      visible={visible}
      mask={false}
      width={520}
      onClose={onClose}>
      <div className={styles.header}>
        <Search
          className={styles.search_input}
          placeholder="搜索过滤器"
          value={value}
          onChange={onInputChange}
          style={{ width: 288, height: 28, flex: 1 }}
        />
        {edit ? (
          <>
            <EasyvButton
              disabled={!selectFilterList.length}
              theme="danger"
              style={{ height: 28, lineHeight: 1, margin: '0 12px' }}
              onClick={() => deleteRef.current?.show()}>
              删除
            </EasyvButton>
            <EasyvButton
              onClick={() => {
                setEdit(false);
                setSelectFilterList([]);
              }}
              style={{ height: 28, lineHeight: 1, display: 'flex', alignItems: 'center' }}
              theme="default">
              取消操作
            </EasyvButton>
            <EasyvModal.Confirm
              title="删除过滤器"
              content="此操作执行后不可逆，是否确认删除？"
              ref={deleteRef}
              onOk={onDeleteFilter}
            />
          </>
        ) : (
          <>
            <EasyvButton
              theme="default"
              className={styles.manage}
              style={{ height: 28, lineHeight: 1, margin: '0 12px' }}
              onClick={() => setEdit(true)}>
              批量管理
            </EasyvButton>
            <EasyvButton
              onClick={() => setAdding(true)}
              style={{ height: 28, lineHeight: 1, display: 'flex', alignItems: 'center' }}
              theme="primary"
              disabled={adding}>
              <PlusOutlined style={{ display: 'flex', marginRight: '4px' }}></PlusOutlined>
              添加过滤器
            </EasyvButton>
          </>
        )}
      </div>

      <ul className={styles.list} style={{ maxHeight: 'calc(100vh - 166px)', overflow: 'auto' }}>
        {adding && !edit && <FilterAdd onSubmit={handleAdd} onRemove={handleRemove} />}
        {edit ? (
          <SelectFilterList
            search={value}
            selectFilterList={selectFilterList}
            setSelectFilterList={setSelectFilterList}
            setFiltersWithComponents={setFiltersWithComponents}
          />
        ) : (
          <FilterList search={value} />
        )}
      </ul>
    </Drawer>
  );
}

export default Filter;
