import React, { useState, useEffect, useCallback } from 'react';
import { Modal } from 'antd';
import { produce } from 'immer';
import cs from 'classnames';
import { fontUrl, fontUrlKeyText } from '../../../config';
import './ModalEditor.less';

const ModalEditor = ({ visible, onOk, onCancel, onChange, name, curType }) => {
  const [iconfList, setIconfList] = useState([]);
  const getData = async () => {
    const links = document
      .getElementsByTagName('head')[0]
      .getElementsByTagName('link');
    let link = fontUrl;
    for (let i = 0; i < links.length; i += 1) {
      if (links[i].href.indexOf(fontUrlKeyText) >= 0) {
        link = links[i].href;
        break;
      }
    }
    const xhr = new XMLHttpRequest();
    xhr.open('GET', link);
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4 && xhr.status === 200) {
        const iconList = xhr.responseText.match(/icon-[\d\w-]{0,}/g);
        const nextData = iconList.map(item => {
          if (item !== curType) {
            return { type: item, selected: false };
          }
          return { type: item, selected: true };
        });
        setIconfList(nextData);
      }
    };
    xhr.send();
  };

  useEffect(() => {
    getData();
  }, []);

  const select = index => {
    const nexticonfList = produce(iconfList, draft => {
      Object.assign(draft[index], { selected: !draft[index].selected });
      if (draft[index].selected) {
        draft.forEach((item, i) => {
          if (i !== index) {
            Object.assign(item, { selected: false });
          }
        });
      }
    });
    setIconfList(nexticonfList);
  };
  const clearSelected = useCallback(() => {
    const nexticonfList = iconfList.map(item => ({
      ...item,
      selected: false,
    }));
    setIconfList(nexticonfList);
  }, [iconfList]);

  const handleOk = () => {
    iconfList.forEach(item => {
      if (item.selected) {
        if (name) {
          onChange(name.type, item.type);
        } else {
          onChange(item.type);
        }
      }
    });

    clearSelected();
    onOk();
  };
  return (
    <Modal
      bodyStyle={{ minHeight: '500px' }}
      visible={visible}
      onOk={handleOk}
      onCancel={onCancel}
      forceRender
    >
      <div className="drawer-item-icon-modal">
        <div className="icon-slot">
          {iconfList.map((item, index) => {
            return (
              <span
                className={cs(
                  'icon-wrap',
                  `icon ${item.type}`,
                  item.selected ? 'icon-wrap--active' : '',
                )}
                key={item.type}
                onClick={() => {
                  select(index);
                }}
                selected={item.selected}
              />
            );
          })}
        </div>
      </div>
    </Modal>
  );
};

export default ModalEditor;
