import { useMutation } from "@apollo/client";
import { Button, Form, notification } from "antd";
import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { UPDATE_JOB } from "../../graphql/jobs.queries";
import DateTimePicker from "../form-date-time-picker/form-date-time-picker.component";
import LayoutFormRow from "../layout-form-row/layout-form-row.component";
import moment from "moment";
import FormDatePicker from "../form-date-picker/form-date-picker.component";
import AuditTrailMapping from "../../utils/AuditTrailMappings";

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { insertAuditTrail } from "../../redux/application/application.actions";

const mapStateToProps = createStructuredSelector({
  //currentUser: selectCurrentUser
});

const mapDispatchToProps = (dispatch) => ({
  insertAuditTrail: ({ jobid, operation }) =>
    dispatch(insertAuditTrail({ jobid, operation })),
});

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

export function JobsAdminDatesChange({ insertAuditTrail, job }) {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [updateJob] = useMutation(UPDATE_JOB);

  const handleFinish = async (values) => {
    setLoading(true);
    const result = await updateJob({
      variables: { jobId: job.id, job: values },
    });

    const changedAuditFields = form.getFieldsValue(
      true,
      (meta) => meta && meta.touched
    );

    Object.keys(changedAuditFields).forEach((key) => {
      insertAuditTrail({
        jobid: job.id,
        operation: AuditTrailMapping.admin_jobfieldchange(
          key,
          changedAuditFields[key] instanceof moment
            ? moment(changedAuditFields[key]).format("MM/DD/YYYY hh:mm a")
            : changedAuditFields[key]
        ),
      });
    });

    if (!!!result.errors) {
      notification["success"]({ message: t("jobs.successes.save") });
    } else {
      notification["error"]({
        message: t("jobs.errors.saving", {
          error: JSON.stringify(result.errors),
        }),
      });
    }
    setLoading(false);
    //Get the owner details, populate it all back into the job.
  };

  useEffect(() => {
    //form.resetFields();
  }, [form, job]);

  return (
    <div>
      <Form
        onFinish={handleFinish}
        autoComplete={"off"}
        form={form}
        layout="vertical"
        initialValues={{
          ...job,
          date_estimated: job.date_estimated
            ? moment(job.date_estimated)
            : null,
        }}
      >
        <LayoutFormRow header={t("jobs.forms.estdates")}>
          <Form.Item
            label={t("jobs.fields.date_estimated")}
            name="date_estimated"
          >
            <FormDatePicker format="MM/DD/YYYY" />
          </Form.Item>
          <Form.Item label={t("jobs.fields.date_towin")} name="date_towin">
            <DateTimePicker />
          </Form.Item>
          <Form.Item
            label={t("jobs.fields.date_rentalresp")}
            name="date_rentalresp"
          >
            <DateTimePicker />
          </Form.Item>
          <Form.Item label={t("jobs.fields.date_open")} name="date_open">
            <DateTimePicker />
          </Form.Item>

          <Form.Item
            label={t("jobs.fields.date_scheduled")}
            name="date_scheduled"
          >
            <DateTimePicker />
          </Form.Item>
          <Form.Item label={t("jobs.fields.scheduled_in")} name="scheduled_in">
            <DateTimePicker />
          </Form.Item>

          <Form.Item label={t("jobs.fields.actual_in")} name="actual_in">
            <DateTimePicker />
          </Form.Item>
          <Form.Item
            label={t("jobs.fields.date_last_contacted")}
            name="date_last_contacted"
          >
            <DateTimePicker />
          </Form.Item>
          <Form.Item
            label={t("jobs.fields.scheduled_completion")}
            name="scheduled_completion"
          >
            <DateTimePicker />
          </Form.Item>
          <Form.Item
            label={t("jobs.fields.actual_completion")}
            name="actual_completion"
          >
            <DateTimePicker />
          </Form.Item>
          <Form.Item
            label={t("jobs.fields.scheduled_delivery")}
            name="scheduled_delivery"
          >
            <DateTimePicker />
          </Form.Item>
          <Form.Item
            label={t("jobs.fields.actual_delivery")}
            name="actual_delivery"
          >
            <DateTimePicker />
          </Form.Item>

          <Form.Item
            label={t("jobs.fields.date_invoiced")}
            name="date_invoiced"
          >
            <DateTimePicker />
          </Form.Item>

          <Form.Item
            label={t("jobs.fields.date_exported")}
            name="date_exported"
          >
            <DateTimePicker />
          </Form.Item>
        </LayoutFormRow>
      </Form>

      <Button loading={loading} onClick={() => form.submit()}>
        {t("general.actions.save")}
      </Button>
    </div>
  );
}
