import React, { memo, useState, useEffect, useCallback } from 'react';
import { connect } from 'react-redux';
import Mousetrap from 'mousetrap';
import EditModal from 'containers/admin-panel/components/modulePanel/EditModal';
import { createModule } from 'models/module';
import { getLabelsByType } from 'services/labelsResource';
import { MaterialSquare } from 'models/adminPanel.types';

function ModuleCreateContainer({ categorys, createModule }) {
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [labelsAllList, setlabelsAllList] = useState<string[]>([]);

  useEffect(() => {
    const showModal = () => {
      setVisible(true);
    };

    const initLabelsAllList = async () => {
      const _labelsAllList = await getLabelsByType(MaterialSquare.TOPIC_RESOURCES);
      setlabelsAllList(_labelsAllList);
    };
    initLabelsAllList();

    Mousetrap.bind(['command+shift+d+2', 'ctrl+shift+d+2'], showModal);
    return () => {
      Mousetrap.unbind(['command+shift+d+2', 'ctrl+shift+d+2']);
    };
  }, []);

  const handleCancel = useCallback(() => {
    setVisible(false);
  }, []);

  const handleOk = useCallback(async (values) => {
    setLoading(true);
    const result = await createModule(values);
    setLoading(false);
    if (result) {
      setVisible(false);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <EditModal
      visible={visible}
      confirmLoading={loading}
      categorys={categorys}
      onCancel={handleCancel}
      onOk={handleOk}
      labelsAllList={labelsAllList}
    />
  );
}

const mapStateToProps = ({ modules }) => {
  return {
    categorys: modules.categorys
  };
};

const mapDispatchToProps = {
  createModule
};

export default connect(mapStateToProps, mapDispatchToProps)(memo(ModuleCreateContainer));
