import { useMutation } from "@apollo/client/react";
import { Button, Form } from "antd";
import dayjs from "../../utils/day";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { UPDATE_JOB } from "../../graphql/jobs.queries";
import AuditTrailMapping from "../../utils/AuditTrailMappings";
import DateTimePicker from "../form-date-time-picker/form-date-time-picker.component";
import FormFieldsChanged from "../form-fields-changed-alert/form-fields-changed-alert.component";
import LayoutFormRow from "../layout-form-row/layout-form-row.component";

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { insertAuditTrail } from "../../redux/application/application.actions";
import { DateTimeFormat } from "./../../utils/DateFormatter";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

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

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

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 notification = useNotification();

  const handleFinish = async (values) => {
    setLoading(true);
    const result = await updateJob({
      variables: { jobId: job.id, job: values },
      refetchQueries: ["GET_JOB_BY_PK"],
      awaitRefetchQueries: true
    });

    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 dayjs ? DateTimeFormat(changedAuditFields[key]) : changedAuditFields[key]
        ),
        type: "admin_jobfieldchange"
      });
    });

    if (!result.errors) {
      notification.success({ title: t("jobs.successes.save") });
    } else {
      notification.error({
        title: t("jobs.errors.saving", {
          error: JSON.stringify(result.errors)
        })
      });
    }

    form.resetFields();

    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 ? dayjs(job.date_estimated) : null
        }}
      >
        <FormFieldsChanged form={form} />
        <LayoutFormRow header={t("jobs.forms.estdates")}>
          <Form.Item label={t("jobs.fields.date_estimated")} name="date_estimated">
            <DateTimePicker format="MM/DD/YYYY" isDateOnly />
          </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.estimate_sent_approval")} name="estimate_sent_approval">
            <DateTimePicker />
          </Form.Item>
          <Form.Item label={t("jobs.fields.estimate_approved")} name="estimate_approved">
            <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_repairstarted")} name="date_repairstarted">
            <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>
          <Form.Item label={t("jobs.fields.date_void")} name="date_void">
            <DateTimePicker />
          </Form.Item>
          <Form.Item label={t("jobs.fields.date_lost_sale")} name="date_lost_sale">
            <DateTimePicker />
          </Form.Item>
        </LayoutFormRow>
      </Form>

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