import { useMutation } from "@apollo/client/react";
import { Button, Card, Dropdown, Space } from "antd";
import { 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 dayjs from "../../utils/day";
import DateTimePicker from "../form-date-time-picker/form-date-time-picker.component.jsx";

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

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

    //e.stopPropagation();

    updateAlert({
      variables: {
        jobId: record.id,
        job: {
          [field]: date
        }
      },
      optimisticResponse: {
        update_jobs: {
          [field]: date
        }
      }
    }).then(() => {
      if (record.refetch) record.refetch();
      if (!time) {
        setOpen(false);
      }
    });
  };

  let className = "";
  if (pastIndicator) {
    className =
      !!record[field] &&
      ((dayjs().isSameOrAfter(dayjs(record[field]), "day") && "production-completion-past") ||
        (dayjs().add(1, "day").isSame(dayjs(record[field]), "day") && "production-completion-soon"));
  }
  // TODO - Client Update = Why is the overlay a card?

  const overlayMenu = {
    items: [
      {
        key: "overlayItem1",
        label: (
          <Card style={{ padding: "1rem" }} onClick={(e) => e.stopPropagation()}>
            <Space orientation={"vertical"}>
              <DateTimePicker
                onClick={(e) => e.stopPropagation()}
                value={(record[field] && dayjs(record[field])) || null}
                onChange={handleChange}
                format={time ? "MM/DD/YYYY hh:mm a" : "MM/DD/YYYY"}
                isDateOnly={!time}
                showTime={time ? { format: "hh:mm a", minuteStep: 15 } : false}
              />
              <Button onClick={() => setOpen(false)}>{t("general.actions.close")}</Button>
            </Space>
          </Card>
        )
      }
    ]
  };

  return (
    <Dropdown
      trigger={["click"]}
      onOpenChange={(v) => setOpen(v)}
      open={open}
      style={{
        height: "19px"
      }}
      menu={overlayMenu}
    >
      <div
        onClick={() => setOpen(true)}
        style={{
          height: "19px",
          cursor: "pointer"
        }}
        className={className}
      >
        <DateFormatter bordered={false}>{record[field]}</DateFormatter>
      </div>
    </Dropdown>
  );
}
