import React, { useState, useRef, useEffect, useCallback } from "react";
import { Time20 } from "@carbon/icons-react";
// import locale from "date-fns/locale/en-US";
import { twMerge } from "tailwind-merge";
import Block from "../../atoms/Block";
import InputMasked from "../InputMasked";
import IMask from 'imask/dist/imask';

export interface InputTimeProps {
  /**
   * Input Ref .
   */
  ref?: React.Ref<HTMLInputElement>;
  /**
   * Value prop that can receive a Date.
   */
  value?: string;
  /**
   * Disable the input and the calendar
   */
  disabled?: boolean;
  /**
   * Main container className.
   */
  className?: string;
  /**
   * Label text for the DateInput.
   */
  label?: string;

  /**
   * Color variation that will switch between styles for the InputTime .
   */
  variation?: "default" | "primary" | "secondary";
  /**
   * onChange event that will return a DateObj.
   */

  onChange?: (value: React.SetStateAction<any>) => void;
}

const InputTime: React.FC<InputTimeProps> = (props) => {
  const { value, disabled, className, variation, onChange } = props;
  const [time, setTime] = useState<
    string | number | readonly string[] | undefined
  >(value);
  const ref = useRef(null);

  const handleOnChange = useCallback(() => {
    if (onChange && time) onChange(time);
  }, [time]);

  useEffect(() => {
    handleOnChange();
  }, [time]);

  const timeBlock = {
    HH: {
      mask: IMask.MaskedRange,
      from: 0,
      to: 23,
    },
    MM: {
      mask: IMask.MaskedRange,
      from: 0,
      to: 59,
    },
  };

  return (
    //TODO: Add block and ref instead of the div
    <div className={twMerge(`relative w-full ${className ? className : ""}`)}>
      <Block className="relative z-20 flex">
        <InputMasked
          ref={ref}
          variation={variation}
          mask={"HH:MM"}
          value={time}
          blocks={timeBlock}
          onComplete={(value) => value && setTime(value)}
          onAccept={(value) => !value && setTime(undefined)}
          placeholder="hh:mm"
          autofix={true}
          disabled={disabled}
        />
        <Block
          className={`flex items-center absolute right-0 inset-y-0 px-3 py-0 z-30
            ${
              variation === "primary" || variation === "secondary"
                ? "text-white"
                : ""
            } 
          `}
        >
          <Time20 className="text-inherit" />
        </Block>
      </Block>
    </div>
  );
};
InputTime.displayName = "InputTime";

export default InputTime;
