import { format } from "date-fns";
import React, { forwardRef } from "react";
import { STATUS_VARIANT } from "../../types";
import { DATE_FORMAT, parseDate } from "../../utilities";
import { bemHOF } from "../../utilities/bem";
import { Box } from "../Box";
import { ICON_TYPE } from "../Icon";
import { Input } from "../Input";
import { Tooltip } from "../Tooltip";

interface CustomDateRangeInputProps {
  value: string;
  setValue: (newVal: string) => void;
  setError: (newError: string) => void;
  error: string;
  ariaLabel: string;
  onFocus: () => void;
}

const cn = bemHOF("DateRangePicker");

const DATE_INPUT_PLACEHOLDER = "--/--/----";

export const CustomDateRangeInput = forwardRef<
  HTMLInputElement,
  CustomDateRangeInputProps
>(({ value, setValue, error, setError, ariaLabel, onFocus }, ref) => {
  return (
    <Tooltip
      placement="top"
      className={cn({ e: "date-input-tooltip" })}
      isVisible={!!error}
      referenceElement={
        <Box>
          <Input
            ref={ref}
            aria-label={ariaLabel}
            variant={error ? STATUS_VARIANT.WARNING : undefined}
            placeholder={DATE_INPUT_PLACEHOLDER}
            className={cn({ e: "date-input" })}
            icon={ICON_TYPE.CALENDAR}
            value={value}
            onChange={(e) => setValue(e.currentTarget.value)}
            onFocus={onFocus}
            onBlur={() => {
              const parsedDate = parseDate(value);
              if (!parsedDate) {
                if (value === "") return;
                setValue("");
                setError("Invalid Date");
                return;
              }
              setError("");
              setValue(format(parsedDate, DATE_FORMAT));
            }}
          />
        </Box>
      }
    >
      {error}
    </Tooltip>
  );
});
