import type { JSX } from "solid-js";
import { Show, splitProps } from "solid-js";
import { useDatePickerContext } from "./date-picker-context";

export interface DatePickerInputProps extends JSX.HTMLAttributes<HTMLInputElement> {
  children?: never;
}

/** Read-only input displaying the formatted selected date. Clicking opens the calendar popover. */
export function DatePickerInput(props: DatePickerInputProps): JSX.Element {
  const [, rest] = splitProps(props, []);
  const ctx = useDatePickerContext();

  const displayValue = () => {
    const v = ctx.value();
    return v ? ctx.formatDate(v) : "";
  };

  const handleClick: JSX.EventHandler<HTMLInputElement, MouseEvent> = (e) => {
    if (typeof props.onClick === "function") props.onClick(e);
    if (!ctx.disabled()) ctx.toggle();
  };

  return (
    <>
      <input
        type="text"
        readOnly
        value={displayValue()}
        placeholder={ctx.placeholder()}
        disabled={ctx.disabled()}
        aria-haspopup="dialog"
        aria-expanded={ctx.isOpen()}
        aria-controls={ctx.contentId()}
        data-state={ctx.isOpen() ? "open" : "closed"}
        onClick={handleClick}
        {...rest}
      />
      <Show when={ctx.name() && ctx.value()}>
        <input type="hidden" name={ctx.name()} value={ctx.value()} />
      </Show>
    </>
  );
}
