import { useMutation, useQuery } from "@apollo/client";
import { Button, Form, Modal, notification, PageHeader, Space } from "antd";
import moment from "moment";
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 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 { data: EmployeeAutoCompleteData } = useQuery(QUERY_ACTIVE_EMPLOYEES, {
    skip: !timeTicketModal.visible,
    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,
            },
          ],
        },
      })
        .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"]);

      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.visible) form.resetFields();
  }, [timeTicketModal.visible, 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
            ? 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%"}
      visible={timeTicketModal.visible}
      forceRender
      onCancel={handleCancel}
      afterClose={() => form.resetFields()}
      footer={
        <span>
          <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>
          )}
        </span>
      }
      destroyOnClose
    >
      <Form
        onFinish={handleFinish}
        layout="vertical"
        autoComplete={"off"}
        form={form}
        onFinishFailed={() => setEnterAgain(false)}
        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
                  ? moment(timeTicketModal.context.timeticket.date)
                  : null,
              }
            : { jobid: timeTicketModal.context.jobId || null }
        }
        onValuesChange={handleFieldsChange}
      >
        <PageHeader
          extra={
            <Space>
              <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}
          employeeAutoCompleteOptions={
            EmployeeAutoCompleteData && EmployeeAutoCompleteData.employees
          }
          employeeSelectDisabled={
            timeTicketModal.context?.timeticket?.employeeid &&
            !timeTicketModal.context.id
              ? true
              : false
          }
        />
      </Form>
    </Modal>
  );
}

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