import { AlertFilled, DownOutlined, LoadingOutlined } from "@ant-design/icons";
import { useMutation } from "@apollo/client";
import { Dropdown, Menu, message, Space } from "antd";
import React, { useState } from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { UPDATE_JOB } from "../../../graphql/jobs.queries";
import ipcTypes from "../../../ipc.types";
import { selectBodyshop } from "../../../redux/user/user.selectors";
import GroupVerifySwitch from "../group-verify-switch/group-verify-switch.component";
import JobsGroupModalMolecule from "../jobs-group-modal/jobs-group-modal.molecule";
const { ipcRenderer } = window;

const mapStateToProps = createStructuredSelector({
  //currentUser: selectCurrentUser
  bodyshop: selectBodyshop,
});
const mapDispatchToProps = (dispatch) => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});
export default connect(mapStateToProps, mapDispatchToProps)(JobGroupMolecule);

export function JobGroupMolecule({ bodyshop, jobId, group, job }) {
  const [loading, setLoading] = useState(false);
  const [updateJob] = useMutation(UPDATE_JOB);

  const handleMenuClick = async (value) => {
    ipcRenderer.send(ipcTypes.app.toMain.track, {
      event: "CHANGE_VEHICLE_GROUP",
      vehicle: `${job.v_model_yr} ${job.v_makedesc} ${job.v_model} (${job.v_type})`,
      oldGroup: group,
      newGroup: value.key,
    });
    setLoading(true);
    const result = await updateJob({
      variables: { jobId: jobId, job: { group: value.key } },
    });

    if (!result.errors) {
      message.success("Vehicle group updated.");
    } else {
      message.error("Error updating job.");
    }
    setLoading(false);
  };

  const menu = (
    <Menu
      onClick={handleMenuClick}
      items={bodyshop.groups.map((g, idx) => ({ key: g, title: g, label: g }))}
    ></Menu>
  );

  return (
    <Space align="top">
      <Dropdown overlay={menu} trigger={["click"]}>
        <a href=" #" onClick={(e) => e.preventDefault()}>
          {group}
          <DownOutlined style={{ marginLeft: ".2rem" }} />
        </a>
      </Dropdown>
      {!group && (
        <div style={{ marginLeft: ".2rem" }}>
          <AlertFilled style={{ color: "tomato" }} className="blink_me" />
          <span style={{ color: "tomato" }}>No group set.</span>
        </div>
      )}
      {group && (
        <div style={{ marginLeft: ".2rem" }}>
          <GroupVerifySwitch
            job={job}
            loading={loading}
            loadingCallback={setLoading}
          />
        </div>
      )}
      <JobsGroupModalMolecule />
      {loading && <LoadingOutlined />}
    </Space>
  );
}
