import React, { ChangeEvent, forwardRef } from "react";

import { Input, InputProps } from "../input/Input";

export interface DatePickerProps
  extends Omit<InputProps, "value" | "onChange"> {
  value: Date | undefined;
  onChange?: (
    e: ChangeEvent<HTMLInputElement>,
    newDate: Date | undefined
  ) => void;
}

/**
 * Generates a timezone-aware ISO string from a Date object.
 *
 * Credit: https://stackoverflow.com/a/17415677/5726823
 */
function toIsoString(date: Date) {
  const tzo = -date.getTimezoneOffset();
  const dif = tzo >= 0 ? "+" : "-";
  const bound = (num: number, digits: number = 2) =>
    String(num).padStart(digits, "0").slice(-digits);

  return `${bound(date.getFullYear(), 4)}-${bound(date.getMonth() + 1)}-${bound(
    date.getDate()
  )}T${bound(date.getHours())}:${bound(date.getMinutes())}:${bound(
    date.getSeconds()
  )}${dif}${bound(Math.floor(Math.abs(tzo) / 60))}:${bound(
    Math.abs(tzo) % 60
  )}`;
}

export const DatePicker = forwardRef<HTMLInputElement, DatePickerProps>(
  ({ value, onChange, ...restProps }, ref) => (
    <Input
      ESCAPE_className="docoli-date-picker"
      value={
        value instanceof Date
          ? toIsoString(value).slice(0, "YYYY-MM-DD".length)
          : ""
      }
      onChange={(e) =>
        onChange?.(
          e as ChangeEvent<HTMLInputElement>,
          e.target.value === "" ? undefined : new Date(e.target.value)
        )
      }
      clearButton={false}
      type="date"
      ref={ref}
      {...restProps}
    />
  )
);
