import { CheckOutlined, CloseOutlined } from "@ant-design/icons";
import { useMutation } from "@apollo/client";
import { Switch } from "antd";
import { antdMessage as message } from "../../../util/antdFeedback";
import React from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { UPDATE_JOB } from "../../../graphql/jobs.queries";
import { toggleGroupVerified } from "../../../redux/reporting/reporting.actions";

const mapStateToProps = createStructuredSelector({});

const mapDispatchToProps = (dispatch) => ({
  toggleGroupVerified: (jobId) => dispatch(toggleGroupVerified(jobId)),
});

export default connect(mapStateToProps, mapDispatchToProps)(GroupVerifySwitch);

export function GroupVerifySwitch({
  job,
  loading,
  loadingCallback,
  toggleGroupVerified,
}) {
  const [updateJob] = useMutation(UPDATE_JOB);

  const handleVerifyGroup = async (val) => {
    if (loadingCallback) loadingCallback(true);
    const result = await updateJob({
      variables: { jobId: job.id, job: { group_verified: val } },
    });

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

  return (
    <Switch
      checkedChildren={<CheckOutlined />}
      unCheckedChildren={<CloseOutlined />}
      disabled={loading}
      checked={job.group_verified}
      onChange={handleVerifyGroup}
    />
  );
}
