import { DatePicker } from "antd";
import PropTypes from "prop-types";
import React, { useCallback, useState } from "react";
import { useTranslation } from "react-i18next";
import dayjs from "../../utils/day";
import { fuzzyMatchDate } from "./formats.js";

const DateTimePicker = ({ value, onChange, onBlur, id, onlyFuture, onlyToday, isDateOnly = false, ...restProps }) => {
  const [isManualInput, setIsManualInput] = useState(false);
  const { t } = useTranslation();

  const handleChange = useCallback(
    (newDate) => {
      if (onChange) {
        onChange(newDate || null);
      }
      setIsManualInput(false);
    },
    [onChange]
  );

  const handleBlur = useCallback(
    (e) => {
      // Bail if this is not a manual input
      if (!isManualInput) {
        return;
      }
      // Reset manual input flag
      setIsManualInput(false);

      const v = e?.target?.value;

      if (!v) return;

      let parsedDate = isDateOnly ? fuzzyMatchDate(v)?.startOf("day") : fuzzyMatchDate(v);

      if (parsedDate && onChange) {
        onChange(parsedDate);
      }
    },
    [isManualInput, isDateOnly, onChange]
  );

  const handleKeyDown = useCallback(
    (e) => {
      setIsManualInput(true);

      if (e.key.toLowerCase() === "t" && onChange) {
        e.preventDefault();
        setIsManualInput(false);
        onChange(dayjs());
      } else if (e.key.toLowerCase() === "enter") {
        handleBlur(e);
      }
    },
    [onChange, handleBlur]
  );

  const handleDisabledDate = useCallback(
    (current) => {
      if (onlyToday) {
        return !dayjs().isSame(current, "day");
      } else if (onlyFuture) {
        return dayjs().subtract(1, "day").isAfter(current);
      }
      return false;
    },
    [onlyToday, onlyFuture]
  );

  return (
    <div onKeyDown={handleKeyDown} id={id} style={{ width: "100%" }}>
      <DatePicker
        showTime={
          isDateOnly
            ? false
            : {
                format: "hh:mm a",
                minuteStep: 15,
                defaultValue: dayjs(dayjs(), "HH:mm:ss")
              }
        }
        format={isDateOnly ? "MM/DD/YYYY" : "MM/DD/YYYY hh:mm a"}
        value={value ? dayjs(value) : null}
        onChange={handleChange}
        placeholder={isDateOnly ? t("general.labels.date") : t("general.labels.datetime")}
        onBlur={onBlur || handleBlur}
        disabledDate={handleDisabledDate}
        {...restProps}
      />
    </div>
  );
};

DateTimePicker.propTypes = {
  value: PropTypes.any,
  onChange: PropTypes.func,
  onBlur: PropTypes.func,
  id: PropTypes.string,
  onlyFuture: PropTypes.bool,
  onlyToday: PropTypes.bool,
  isDateOnly: PropTypes.bool
};

export default React.memo(DateTimePicker);
