import * as React from "react";
import { CalendarDays } from "lucide-react";
import { fmtDate, parseTypedDate } from "@/lib/dates";
import { cn } from "@/lib/utils";

const BASE =
  "flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm";
const shown = (iso: unknown) => (typeof iso === "string" && iso ? fmtDate(iso) : "");

/**
 * DD/MM/YYYY in every browser: the browser's own date box follows the language of the computer.
 * The hidden native box keeps the value (ISO), fires the change and opens the calendar.
 */
function DateInput({
  className,
  value,
  disabled,
  id,
  required,
  ...props
}: React.ComponentProps<"input">) {
  const native = React.useRef<HTMLInputElement>(null);
  const [text, setText] = React.useState(shown(value));
  const last = React.useRef(value);
  React.useEffect(() => {
    if (value !== last.current) {
      last.current = value;
      setText(shown(value));
    }
  }, [value]);
  const send = (iso: string) => {
    const el = native.current;
    if (!el || el.value === iso) return;
    last.current = iso;
    Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(el, iso);
    el.dispatchEvent(new Event("input", { bubbles: true }));
  };
  const typed = (raw: string) => {
    // A pasted 2026-11-20 becomes 20/11/2026.
    const t = /^\d{4}-\d{2}-\d{2}$/.test(raw) ? fmtDate(raw) : raw;
    // Slashes appear by themselves while typing digits.
    const d =
      t.length > text.length
        ? t.replace(/^(\d{2})(\d)$/, "$1/$2").replace(/^(\d{2}\/\d{2})(\d)/, "$1/$2")
        : t;
    setText(d);
    const p = parseTypedDate(d);
    send(p.kind === "ok" ? p.iso : "");
  };
  const wrong = text.length > 0 && parseTypedDate(text).kind !== "ok";
  return (
    <span className="relative block">
      <input
        id={id}
        type="text"
        inputMode="numeric"
        autoComplete="off"
        placeholder="DD/MM/YYYY"
        maxLength={10}
        value={text}
        disabled={disabled}
        required={required}
        aria-label={props["aria-label"]}
        aria-invalid={props["aria-invalid"] || (wrong && text.length === 10) || undefined}
        onChange={(e) => typed(e.target.value)}
        className={cn(
          BASE,
          "pr-9 tabular",
          wrong && text.length === 10 && "border-danger",
          className,
        )}
      />
      <button
        type="button"
        disabled={disabled}
        aria-label="Open the calendar"
        onClick={(e) => {
          e.preventDefault();
          native.current?.showPicker?.();
        }}
        className="absolute right-0 top-0 flex h-9 w-9 items-center justify-center text-muted-foreground hover:text-foreground disabled:opacity-50"
      >
        <CalendarDays className="h-4 w-4" aria-hidden />
      </button>
      <input
        {...props}
        ref={native}
        type="date"
        value={value}
        disabled={disabled}
        tabIndex={-1}
        aria-hidden
        className="pointer-events-none absolute bottom-0 right-0 h-px w-px opacity-0"
      />
    </span>
  );
}

const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
  ({ className, type, ...props }, ref) =>
    type === "date" ? (
      <DateInput className={className} {...props} />
    ) : (
      <input type={type} className={cn(BASE, className)} ref={ref} {...props} />
    ),
);
Input.displayName = "Input";

export { Input };
