"use client";

import { useRef, useState } from "react";
import { FieldErrorIcon } from "./Field";

const MONTHS = [
  ["01", "January"],
  ["02", "February"],
  ["03", "March"],
  ["04", "April"],
  ["05", "May"],
  ["06", "June"],
  ["07", "July"],
  ["08", "August"],
  ["09", "September"],
  ["10", "October"],
  ["11", "November"],
  ["12", "December"],
] as const;

interface Parts {
  day: string;
  month: string;
  year: string;
}

const EMPTY: Parts = { day: "", month: "", year: "" };

function splitIso(iso: string): Parts {
  const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec((iso || "").trim().slice(0, 10));
  if (!match) return EMPTY;
  return { year: match[1], month: match[2], day: match[3] };
}

/**
 * Compose to ISO, or "" if any part is missing.
 *
 * A structurally complete but impossible date (31 February) is still emitted,
 * on purpose: the schema's date parser then reports "Invalid date", which is
 * the true problem. Swallowing it to "" would report "required" instead and
 * send the traveller looking at a field they have already filled in.
 */
function joinIso(parts: Parts): string {
  const day = parts.day.trim();
  const month = parts.month.trim();
  const year = parts.year.trim();
  if (!day || !month || year.length !== 4) return "";
  return `${year}-${month.padStart(2, "0")}-${day.padStart(2, "0")}`;
}

export interface DatePartsProps {
  /** Base id. Sub-fields get `${id}-day|month|year`; `${id}-day` is the summary anchor. */
  id: string;
  legend: string;
  /** ISO `YYYY-MM-DD`, or "" when incomplete. */
  value: string;
  onChange: (iso: string) => void;
  /** Fired when focus leaves the whole group — drives `mode: "onTouched"`. */
  onBlur?: () => void;
  required?: boolean;
  error?: string;
  hint?: string;
  /** Set for a person's own birthday so browsers can autofill (WCAG 2.2 SC 1.3.5). */
  autoCompleteKind?: "bday" | "off";
  disabled?: boolean;
}

/**
 * Day / Month / Year as three controls inside a `<fieldset>`, following the
 * GOV.UK and NHS date-input pattern.
 *
 * A single `<input type="date">` is the wrong tool for both fields this
 * replaces: reaching 1972 in a calendar picker takes dozens of interactions,
 * and the text fallback flips between dd/mm and mm/dd by locale, which on a
 * passport form is a silent data error rather than a validation failure. A
 * named month removes the ambiguity outright.
 */
export default function DateParts({
  id,
  legend,
  value,
  onChange,
  onBlur,
  required,
  error,
  hint,
  autoCompleteKind = "off",
  disabled,
}: DatePartsProps) {
  const [parts, setParts] = useState<Parts>(() => splitIso(value));
  const monthRef = useRef<HTMLSelectElement | null>(null);
  const groupRef = useRef<HTMLDivElement | null>(null);

  // Adjust state during render when `value` changes from the outside, rather
  // than syncing it in an effect — an effect would paint the stale parts first
  // and then re-render.
  //
  // The second condition is what protects a half-typed date: an incomplete
  // entry emits "", so the prop legitimately goes back to "" while `parts`
  // still holds a day and a month. Overwriting on every prop change would
  // erase what the traveller is in the middle of typing.
  const [syncedFrom, setSyncedFrom] = useState(value);
  if (value !== syncedFrom) {
    setSyncedFrom(value);
    if (value !== joinIso(parts)) setParts(splitIso(value));
  }

  function update(next: Partial<Parts>) {
    const merged = { ...parts, ...next };
    setParts(merged);
    onChange(joinIso(merged));
  }

  function digitsOnly(raw: string, max: number) {
    return raw.replace(/\D/g, "").slice(0, max);
  }

  /** Blur only counts once focus has actually left all three controls. */
  function handleBlur(event: React.FocusEvent<HTMLDivElement>) {
    if (!onBlur) return;
    const next = event.relatedTarget as Node | null;
    if (next && groupRef.current?.contains(next)) return;
    onBlur();
  }

  const describedBy = [hint ? `${id}-hint` : null, error ? `${id}-error` : null]
    .filter(Boolean)
    .join(" ");
  const bday = autoCompleteKind === "bday";
  const invalid = error ? "lf-control--invalid" : "";

  return (
    <fieldset
      className="lf-radiogroup"
      aria-describedby={describedBy || undefined}
      aria-invalid={error ? true : undefined}
      aria-required={required ? true : undefined}
    >
      <legend className="lf-label">
        {legend}
        {required ? (
          <span className="lf-required" aria-hidden="true">
            *
          </span>
        ) : null}
      </legend>

      <div className="lf-dateparts" ref={groupRef} onBlur={handleBlur}>
        <div className="lf-datepart">
          <label className="lf-label lf-datepart-label" htmlFor={`${id}-day`}>
            Day
          </label>
          <input
            id={`${id}-day`}
            className={`lf-control ${invalid}`}
            inputMode="numeric"
            placeholder="DD"
            maxLength={2}
            autoComplete={bday ? "bday-day" : "off"}
            disabled={disabled}
            value={parts.day}
            onChange={(e) => {
              const day = digitsOnly(e.target.value, 2);
              update({ day });
              // Two digits can only be a complete day, so move on. One digit
              // might still be the start of "1" -> "12", so it must not.
              if (day.length === 2) monthRef.current?.focus();
            }}
            onKeyDown={(e) => {
              // "/" and "-" are how people type dates; treat them as "next field".
              if (e.key === "/" || e.key === "-") {
                e.preventDefault();
                monthRef.current?.focus();
              }
            }}
          />
        </div>

        <div className="lf-datepart">
          <label className="lf-label lf-datepart-label" htmlFor={`${id}-month`}>
            Month
          </label>
          <select
            id={`${id}-month`}
            ref={monthRef}
            className={`lf-control ${invalid}`}
            autoComplete={bday ? "bday-month" : "off"}
            disabled={disabled}
            value={parts.month}
            onChange={(e) => update({ month: e.target.value })}
          >
            <option value="">Month</option>
            {MONTHS.map(([code, name]) => (
              <option key={code} value={code}>
                {name}
              </option>
            ))}
          </select>
        </div>

        <div className="lf-datepart">
          <label className="lf-label lf-datepart-label" htmlFor={`${id}-year`}>
            Year
          </label>
          <input
            id={`${id}-year`}
            className={`lf-control ${invalid}`}
            inputMode="numeric"
            placeholder="YYYY"
            maxLength={4}
            autoComplete={bday ? "bday-year" : "off"}
            disabled={disabled}
            value={parts.year}
            onChange={(e) => update({ year: digitsOnly(e.target.value, 4) })}
          />
        </div>
      </div>

      {hint ? (
        <p className="lf-hint" id={`${id}-hint`} style={{ marginTop: 6 }}>
          {hint}
        </p>
      ) : null}

      {error ? (
        <p className="lf-error" id={`${id}-error`} style={{ marginTop: 6 }}>
          <FieldErrorIcon />
          <span>{error}</span>
        </p>
      ) : null}
    </fieldset>
  );
}
