import { AbsoluteTime } from "@gnu-taler/taler-util";
import { InputLine, UIFormProps } from "./InputLine.js";
import { CalendarIcon } from "@heroicons/react/24/outline";
import { VNode, h } from "preact";
import { format, parse } from "date-fns";

export function InputDate(
  props: { pattern?: string } & UIFormProps<AbsoluteTime>,
): VNode {
  const pattern = props.pattern ?? "dd/MM/yyyy";
  return (
    <InputLine<AbsoluteTime>
      type="text"
      after={{
        type: "icon",
        icon: <CalendarIcon class="h-6 w-6" />,
      }}
      converter={{
        fromStringUI: (v) => {
          if (!v) return { t_ms: "never" };
          console.log("from", v);
          const t_ms = parse(v, pattern, Date.now()).getTime();
          return { t_ms };
        },
        toStringUI: (v) => {
          return v === undefined
            ? ""
            : v.t_ms === "never"
            ? "never"
            : format(v.t_ms, pattern);
        },
      }}
      {...props}
    />
  );
}
