import { WarningOutlined } from "@ant-design/icons";
import { useMutation } from "@apollo/client";
import { DatePicker, Space, Spin } from "antd";
import { antdMessage as message, antdNotification as notification } from "../../../util/antdFeedback";
import React, { useState } from "react";
import { UPDATE_JOB } from "../../../graphql/jobs.queries";
import ipcTypes from "../../../ipc.types";
import { CalculateVehicleAge } from "../../../ipc/ipc-estimate-utils";
import { ChangeOfRuleSet, DateFormat } from "../../../util/constants";
import dayjs from "../../../util/day.js";
const { ipcRenderer } = window;

export default function CloseDateDisplayMolecule({ job, jobId, close_date }) {
  const [value, setValue] = useState(dayjs(close_date));
  const [loading, setLoading] = useState(false);
  const [updateJob] = useMutation(UPDATE_JOB);

  const handleChange = async (newDate) => {
    ipcRenderer.send(ipcTypes.app.toMain.track, {
      event: "SET_CLOSED_DATE"
    });
    setLoading(true);
    setValue(newDate);
    const requires_reimport = ChangeOfRuleSet({
      prevDateMoment: job.close_date ? dayjs(job.close_date) : dayjs(job.created_at),
      newDateMoment: newDate ? newDate : dayjs()
    });
    if (requires_reimport) {
      notification.open({
        type: "warning",
        message:
          "Changing the close date has changed the applicable ruleset. Please re-import the job for accurate scoring."
      });
    }

    const result = await updateJob({
      variables: {
        jobId: jobId,
        job: {
          close_date: newDate,
          v_age: CalculateVehicleAge({ ...job, close_date: newDate }),
          requires_reimport: job.requires_reimport || requires_reimport
        }
      }
    });

    if (!result.errors) {
      message.success("Close date updated.");
    } else {
      message.error("Error updating job.");
    }
    setLoading(false);
  };

  return (
    <div>
      <DatePicker value={value && value.isValid() ? value : null} onChange={handleChange} format={DateFormat} />
      {loading && <Spin size="small" />}
      {value && !value.isValid() && (
        <Space size="small">
          <WarningOutlined className="blink_me" style={{ color: "tomato" }} />
          <span>No date set.</span>
        </Space>
      )}
    </div>
  );
}
