import { PageHeader } from "@ant-design/pro-layout";
import { useMutation, useQuery } from "@apollo/client";
import { useSplitTreatments } from "@splitsoftware/splitio-react";
import { Button, Form, Modal, notification, Space } from "antd";
import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { QUERY_ACTIVE_EMPLOYEES } from "../../graphql/employees.queries";
import { INSERT_NEW_TIME_TICKET, UPDATE_TIME_TICKET } from "../../graphql/timetickets.queries";
import { toggleModalVisible } from "../../redux/modals/modals.actions";
import { selectTimeTicket } from "../../redux/modals/modals.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";
import dayjs from "../../utils/day";
import TimeTicketsCommitToggleComponent from "../time-tickets-commit-toggle/time-tickets-commit-toggle.component";
import TimeTicketModalComponent from "./time-ticket-modal.component";

const mapStateToProps = createStructuredSelector({
  timeTicketModal: selectTimeTicket,
  bodyshop: selectBodyshop
});
const mapDispatchToProps = (dispatch) => ({
  toggleModalVisible: () => dispatch(toggleModalVisible("timeTicket"))
});

export function TimeTicketModalContainer({ timeTicketModal, toggleModalVisible, bodyshop }) {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const { t } = useTranslation();
  const [enterAgain, setEnterAgain] = useState(false);
  const [insertTicket] = useMutation(INSERT_NEW_TIME_TICKET);
  const [updateTicket] = useMutation(UPDATE_TIME_TICKET);
  const {
    treatments: { Enhanced_Payroll }
  } = useSplitTreatments({
    attributes: {},
    names: ["Enhanced_Payroll"],
    splitKey: bodyshop.imexshopid
  });

  const { data: EmployeeAutoCompleteData } = useQuery(QUERY_ACTIVE_EMPLOYEES, {
    skip: !timeTicketModal.open,
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

  const handleFinish = (values) => {
    setLoading(true);
    const emps = EmployeeAutoCompleteData.employees.filter((e) => e.id === values.employeeid);
    if (timeTicketModal.context.id) {
      updateTicket({
        variables: {
          timeticketId: timeTicketModal.context.id,
          timeticket: {
            ...values,
            rate: emps.length === 1 ? emps[0].rates.filter((r) => r.cost_center === values.cost_center)[0]?.rate : null
          }
        }
      })
        .then(handleMutationSuccess)
        .catch(handleMutationError);
    } else {
      //Get selected employee rate.
      insertTicket({
        variables: {
          timeTicketInput: [
            {
              ...values,
              rate:
                emps.length === 1 ? emps[0].rates.filter((r) => r.cost_center === values.cost_center)[0].rate : null,
              bodyshopid: bodyshop.id,
              created_by: timeTicketModal.context.created_by
            }
          ]
        }
      })
        .then(handleMutationSuccess)
        .catch(handleMutationError);
    }
  };

  const handleMutationSuccess = (response) => {
    notification["success"]({
      message: t("timetickets.successes.created")
    });
    if (timeTicketModal.actions.refetch) timeTicketModal.actions.refetch();
    if (enterAgain) {
      //Capture the existing information and repopulate it.

      const prev = form.getFieldsValue(["date", "employeeid", "flat_rate"]);

      form.resetFields();

      form.setFieldsValue(prev);
    } else {
      toggleModalVisible();
    }
    setEnterAgain(false);
    setLoading(false);
  };

  const handleMutationError = (error) => {
    setEnterAgain(false);
    notification["error"]({
      message: t("timetickets.errors.creating", {
        message: JSON.stringify(error)
      })
    });
    setLoading(false);
  };

  const handleCancel = () => {
    toggleModalVisible();
  };

  useEffect(() => {
    if (enterAgain) form.submit();
  }, [enterAgain, form]);

  useEffect(() => {
    if (timeTicketModal.open) form.resetFields();
  }, [timeTicketModal.open, form]);

  const handleFieldsChange = (changedFields, allFields) => {
    if (!!changedFields.employeeid && !!EmployeeAutoCompleteData) {
      const emps = EmployeeAutoCompleteData.employees.filter((e) => e.id === changedFields.employeeid);
      form.setFieldsValue({
        cost_center: emps.length > 0 ? emps[0].cost_center : "",
        ciecacode:
          Object.keys(bodyshop.md_responsibility_centers.defaults.costs).find(
            (key) => bodyshop.md_responsibility_centers.defaults.costs[key] === emps[0].cost_center
          ) || "LAB"
      });
    }
    if (!!changedFields.cost_center && !!EmployeeAutoCompleteData) {
      form.setFieldsValue({
        ciecacode:
          bodyshop.cdk_dealerid || bodyshop.pbs_serialnumber || Enhanced_Payroll.treatment === "on"
            ? changedFields.cost_center
            : Object.keys(bodyshop.md_responsibility_centers.defaults.costs).find(
                (key) => bodyshop.md_responsibility_centers.defaults.costs[key] === changedFields.cost_center
              )
      });
    }
  };

  return (
    <Modal
      title={
        timeTicketModal.context && timeTicketModal.context.id
          ? t("timetickets.labels.edit")
          : t("timetickets.labels.new")
      }
      width={"90%"}
      open={timeTicketModal.open}
      forceRender
      onCancel={handleCancel}
      afterClose={() => form.resetFields()}
      footer={
        <Space>
          <Button onClick={handleCancel}>{t("general.actions.cancel")}</Button>
          <Button
            loading={loading}
            disabled={timeTicketModal.context?.timeticket?.committed_at}
            onClick={() => form.submit()}
          >
            {t("general.actions.save")}
          </Button>
          {timeTicketModal.context && timeTicketModal.context.id ? null : (
            <Button
              type="primary"
              loading={loading}
              onClick={() => {
                setEnterAgain(true);
              }}
            >
              {t("general.actions.saveandnew")}
            </Button>
          )}
        </Space>
      }
      destroyOnClose
    >
      <Form
        onFinish={handleFinish}
        layout="vertical"
        autoComplete={"off"}
        form={form}
        onFinishFailed={() => setEnterAgain(false)}
        disabled={timeTicketModal.context?.timeticket?.committed_at}
        initialValues={
          timeTicketModal.context.timeticket
            ? {
                ...timeTicketModal.context.timeticket,
                jobid:
                  (timeTicketModal.context.timeticket.job && timeTicketModal.context.timeticket.job.id) ||
                  timeTicketModal.context.timeticket.jobid ||
                  null,
                date: timeTicketModal.context.timeticket.date ? dayjs(timeTicketModal.context.timeticket.date) : null
              }
            : { jobid: timeTicketModal.context.jobId || null }
        }
        onValuesChange={handleFieldsChange}
      >
        <PageHeader
          extra={
            <Space>
              {Enhanced_Payroll.treatment === "on" && (
                <TimeTicketsCommitToggleComponent timeticket={timeTicketModal.context?.timeticket} />
              )}
              <Button onClick={handleCancel}>{t("general.actions.cancel")}</Button>
              <Button loading={loading} onClick={() => form.submit()}>
                {t("general.actions.save")}
              </Button>
              {timeTicketModal.context && timeTicketModal.context.id ? null : (
                <Button
                  type="primary"
                  loading={loading}
                  onClick={() => {
                    setEnterAgain(true);
                  }}
                >
                  {t("general.actions.saveandnew")}
                </Button>
              )}
            </Space>
          }
        />
        <TimeTicketModalComponent
          isEdit={timeTicketModal.context.id}
          form={form}
          disabled={timeTicketModal.context?.timeticket?.committed_at}
          employeeAutoCompleteOptions={EmployeeAutoCompleteData && EmployeeAutoCompleteData.employees}
          employeeSelectDisabled={
            timeTicketModal.context?.timeticket?.committed_at ||
            (timeTicketModal.context?.timeticket?.employeeid && !timeTicketModal.context.id ? true : false)
          }
        />
      </Form>
    </Modal>
  );
}

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