import { DownCircleFilled } from "@ant-design/icons";
import { useMutation } from "@apollo/client";
import { Button, Dropdown, notification } from "antd";
import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { UPDATE_JOB_STATUS } from "../../graphql/jobs.queries";
import { insertAuditTrail } from "../../redux/application/application.actions";
import { selectJobReadOnly } from "../../redux/application/application.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";
import AuditTrailMapping from "../../utils/AuditTrailMappings";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  jobRO: selectJobReadOnly
});
const mapDispatchToProps = (dispatch) => ({
  insertAuditTrail: ({ jobid, operation, type }) => dispatch(insertAuditTrail({ jobid, operation, type }))
});

export function JobsChangeStatus({ job, bodyshop, jobRO, insertAuditTrail }) {
  const { t } = useTranslation();

  const [availableStatuses, setAvailableStatuses] = useState([]);
  const [otherStages, setOtherStages] = useState([]);
  const [mutationUpdateJobstatus] = useMutation(UPDATE_JOB_STATUS);
  const updateJobStatus = (status) => {
    mutationUpdateJobstatus({
      variables: { jobId: job.id, status: status }
    })
      .then((r) => {
        notification["success"]({ message: t("jobs.successes.save") });
        insertAuditTrail({
          jobid: job.id,
          operation: AuditTrailMapping.jobstatuschange(status),
          type: "jobstatuschange"
        });
        // refetch();
      })
      .catch((error) => {
        notification["error"]({ message: t("jobs.errors.saving") });
      });
  };

  useEffect(() => {
    //Figure out what scenario were in, populate accodingly
    if (job && bodyshop) {
      if (bodyshop.md_ro_statuses.pre_production_statuses.includes(job.status)) {
        setAvailableStatuses(bodyshop.md_ro_statuses.pre_production_statuses);
        if (bodyshop.md_ro_statuses.production_statuses[0])
          setOtherStages([bodyshop.md_ro_statuses.production_statuses[0]]);
      } else if (bodyshop.md_ro_statuses.production_statuses.includes(job.status)) {
        setAvailableStatuses(bodyshop.md_ro_statuses.production_statuses);
        setOtherStages([bodyshop.md_ro_statuses.default_imported, bodyshop.md_ro_statuses.default_delivered]);
      } else if (bodyshop.md_ro_statuses.post_production_statuses.includes(job.status)) {
        setAvailableStatuses(
          bodyshop.md_ro_statuses.post_production_statuses.filter(
            (s) => s !== bodyshop.md_ro_statuses.default_invoiced && s !== bodyshop.md_ro_statuses.default_exported
          )
        );
        if (bodyshop.md_ro_statuses.production_statuses[0])
          setOtherStages([bodyshop.md_ro_statuses.production_statuses[0]]);
      } else {
        console.log("Status didn't match any restrictions. Allowing all status changes.");
        setAvailableStatuses(bodyshop.md_ro_statuses.statuses);
      }
    }
  }, [job, setAvailableStatuses, bodyshop]);

  const statusMenu = {
    items: [
      ...availableStatuses.map((item) => ({
        key: item,
        label: item
      })),
      ...(job.converted
        ? [
            { type: "divider" },
            ...otherStages.map((item) => ({
              key: item,
              label: item
            }))
          ]
        : [])
    ],
    onClick: (e) => updateJobStatus(e.key)
  };

  return (
    <Dropdown menu={statusMenu} trigger={["click"]} key="changestatus" disabled={jobRO || !job.converted}>
      <Button shape="round">
        <span>{job.status}</span>

        <DownCircleFilled />
      </Button>
    </Dropdown>
  );
}

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