import { useMutation } from "@apollo/client";
import { Button, Form, notification, Popover, Space } from "antd";
import dayjs from "dayjs";
import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { JOB_PRODUCTION_TOGGLE } 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";
import { DateTimeFormatterFunction } from "../../utils/DateFormatter";
import FormDateTimePickerComponent from "../form-date-time-picker/form-date-time-picker.component";

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

export function JobsDetailHeaderActionsToggleProduction({ bodyshop, job, jobRO, insertAuditTrail }) {
  const [scenario, setScenario] = useState(false);
  const [loading, setLoading] = useState(false);
  const [mutationUpdateJob] = useMutation(JOB_PRODUCTION_TOGGLE);
  const { t } = useTranslation();
  const [form] = Form.useForm();

  useEffect(() => {
    //Figure out what scenario were in, populate accodingly
    if (job && bodyshop) {
      if (bodyshop.md_ro_statuses.pre_production_statuses.includes(job.status)) {
        setScenario("pre");
      } else if (bodyshop.md_ro_statuses.production_statuses.includes(job.status)) {
        setScenario("prod");
      } else {
        setScenario("post");
      }
    }
  }, [job, setScenario, bodyshop]);

  const handleConvert = async (values) => {
    setLoading(true);
    const res = await mutationUpdateJob({
      variables: {
        jobId: job.id,
        job: {
          ...values,
          status:
            scenario === "pre" ? bodyshop.md_ro_statuses.default_arrived : bodyshop.md_ro_statuses.default_delivered,
          inproduction: scenario === "pre" ? true : false
        }
      }
    });

    if (!res.errors) {
      notification["success"]({
        message: t("jobs.successes.converted")
      });

      insertAuditTrail({
        jobid: job.id,
        operation:
          scenario === "pre"
            ? AuditTrailMapping.jobintake(
                res.data.update_jobs.returning[0].status,
                DateTimeFormatterFunction(values.scheduled_completion)
              )
            : AuditTrailMapping.jobdelivery(
                res.data.update_jobs.returning[0].status,
                DateTimeFormatterFunction(values.actual_completion)
              )
      });
    }
    setLoading(false);
  };

  const popMenu = (
    <div onClick={(e) => e.stopPropagation()}>
      <Form
        layout="vertical"
        form={form}
        onFinish={handleConvert}
        initialValues={{
          actual_in: dayjs(),
          scheduled_completion: job.scheduled_completion,
          actual_completion: job.actual_completion,
          scheduled_deliver: job.scheduled_deliver,
          actual_delivery: job.actual_delivery
        }}
      >
        {scenario === "pre" && (
          <>
            <Form.Item
              name={["actual_in"]}
              label={t("jobs.fields.actual_in")}
              rules={[
                {
                  required: true
                  //message: t("general.validation.required"),
                }
              ]}
            >
              <FormDateTimePickerComponent disabled={jobRO} />
            </Form.Item>
            <Form.Item
              name={["scheduled_completion"]}
              label={t("jobs.fields.scheduled_completion")}
              rules={[
                {
                  required: true
                  //message: t("general.validation.required"),
                }
              ]}
            >
              <FormDateTimePickerComponent disabled={jobRO} />
            </Form.Item>
            <Form.Item name={["scheduled_delivery"]} label={t("jobs.fields.scheduled_delivery")}>
              <FormDateTimePickerComponent disabled={jobRO} />
            </Form.Item>
          </>
        )}
        {scenario === "prod" && (
          <>
            <Form.Item
              name={["actual_completion"]}
              label={t("jobs.fields.actual_completion")}
              rules={[
                {
                  required: true
                  //message: t("general.validation.required"),
                }
              ]}
            >
              <FormDateTimePickerComponent disabled={jobRO} />
            </Form.Item>

            <Form.Item name={["actual_delivery"]} label={t("jobs.fields.actual_delivery")}>
              <FormDateTimePickerComponent disabled={jobRO} />
            </Form.Item>
          </>
        )}

        <Space wrap>
          <Button type="primary" onClick={() => form.submit()} loading={loading}>
            {t("general.actions.save")}
          </Button>
          <Button
            disabled={scenario === "post"}
            onClick={() => {
              //  setOpen(false);
            }}
          >
            {t("general.actions.close")}
          </Button>
        </Space>
      </Form>
    </div>
  );

  return (
    <Popover //open={open}
      content={popMenu}
      onClick={(e) => e.stopPropagation()}
      getPopupContainer={(trigger) => trigger.parentNode}
      trigger="click"
    >
      {scenario === "pre" && t("jobs.actions.intake")}
      {scenario === "prod" && t("jobs.actions.deliver")}
    </Popover>
  );
}

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