import { useMutation } from "@apollo/client";
import { Button, Card, Dropdown, TimePicker } from "antd";
import moment from "moment";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { UPDATE_JOB } from "../../graphql/jobs.queries";
import { DateFormatter } from "../../utils/DateFormatter";
import FormDatePicker from "../form-date-picker/form-date-picker.component";

export default function ProductionListDate({
  record,
  field,
  time,
  pastIndicator,
}) {
  const [updateAlert] = useMutation(UPDATE_JOB);
  const [visible, setVisible] = useState(false);
  const { t } = useTranslation();

  const handleChange = (date) => {
    logImEXEvent("product_toggle_date", { field });
    // if (date.isSame(record[field] && moment(record[field]))) {
    //   return;
    // }

    //e.stopPropagation();
    updateAlert({
      variables: {
        jobId: record.id,
        job: {
          [field]: date,
        },
      },
    }).then(() => {
      if (record.refetch) record.refetch();
      if (!time) {
        setVisible(false);
      }
    });
  };

  let className = "";
  if (pastIndicator) {
    className =
      !!record[field] &&
      ((moment().isSameOrAfter(moment(record[field]), "day") &&
        "production-completion-past") ||
        (moment().add(1, "day").isSame(moment(record[field]), "day") &&
          "production-completion-soon"));
  }
  return (
    <Dropdown
      //trigger={["click"]}
      visible={visible}
      style={{
        height: "19px",
      }}
      overlay={
        <Card style={{ padding: "1rem" }} onClick={(e) => e.stopPropagation()}>
          <FormDatePicker
            onClick={(e) => e.stopPropagation()}
            value={(record[field] && moment(record[field])) || null}
            onChange={handleChange}
            format="MM/DD/YYYY"
            isDateOnly={!time}
          />
          {time && (
            <TimePicker
              onClick={(e) => e.stopPropagation()}
              value={(record[field] && moment(record[field])) || null}
              onChange={handleChange}
              minuteStep={15}
              format="hh:mm a"
            />
          )}
          <Button onClick={() => setVisible(false)}>
            {t("general.actions.close")}
          </Button>
        </Card>
      }
    >
      <div
        onClick={() => setVisible(true)}
        style={{
          height: "19px",
        }}
        className={className}
      >
        <DateFormatter bordered={false}>{record[field]}</DateFormatter>
      </div>
    </Dropdown>
  );
}
