"use client";

/**
 * DateInput — always displays dd/mm/yyyy regardless of browser/OS locale.
 *
 * - Text field shows and accepts dd/mm/yyyy (auto-inserts slashes while typing)
 * - Calendar icon opens a hidden <input type="date"> for native picker
 * - Internal value / onChange contract: yyyy-mm-dd strings (same as <input type="date">)
 */

import { useState, useEffect, useRef } from "react";
import { clsx } from "clsx";

// ── Conversion helpers ────────────────────────────────────────────────────────

function isoToDisplay(iso: string): string {
  if (!iso) return "";
  const [y, m, d] = iso.split("-");
  if (!y || !m || !d) return "";
  return `${d}/${m}/${y}`;
}

function displayToISO(display: string): string {
  const digits = display.replace(/\D/g, "");
  if (digits.length !== 8) return "";
  const d = digits.slice(0, 2);
  const m = digits.slice(2, 4);
  const y = digits.slice(4, 8);
  if (parseInt(d) < 1 || parseInt(d) > 31) return "";
  if (parseInt(m) < 1 || parseInt(m) > 12) return "";
  if (parseInt(y) < 1900 || parseInt(y) > 2100) return "";
  return `${y}-${m}-${d}`;
}

// Auto-insert slashes as the user types
function autoSlash(raw: string): string {
  const digits = raw.replace(/\D/g, "").slice(0, 8);
  if (digits.length <= 2) return digits;
  if (digits.length <= 4) return `${digits.slice(0, 2)}/${digits.slice(2)}`;
  return `${digits.slice(0, 2)}/${digits.slice(2, 4)}/${digits.slice(4)}`;
}

// ── Component ─────────────────────────────────────────────────────────────────

interface DateInputProps {
  value: string;                    // yyyy-mm-dd (empty string = unset)
  onChange: (v: string) => void;    // called with yyyy-mm-dd when valid
  id?: string;
  className?: string;
  required?: boolean;
  min?: string;                     // yyyy-mm-dd
  max?: string;                     // yyyy-mm-dd
  disabled?: boolean;
}

export function DateInput({
  value,
  onChange,
  id,
  className,
  required,
  min,
  max,
  disabled,
}: DateInputProps) {
  const [display, setDisplay] = useState(isoToDisplay(value));
  const hiddenRef = useRef<HTMLInputElement>(null);

  // Sync display when value is changed externally
  useEffect(() => {
    setDisplay(isoToDisplay(value));
  }, [value]);

  function handleTextChange(e: React.ChangeEvent<HTMLInputElement>) {
    const formatted = autoSlash(e.target.value);
    setDisplay(formatted);
    const iso = displayToISO(formatted);
    if (iso) onChange(iso);
  }

  function handleBlur() {
    // Re-normalise display to canonical format on blur
    const iso = displayToISO(display);
    if (iso) {
      setDisplay(isoToDisplay(iso));
    } else if (display && display.replace(/\D/g, "").length < 8) {
      // Incomplete — keep as-is so user can fix it
    } else if (!display) {
      // Cleared
      setDisplay("");
    }
  }

  function handleHiddenChange(e: React.ChangeEvent<HTMLInputElement>) {
    const iso = e.target.value; // yyyy-mm-dd from native picker
    if (iso) {
      setDisplay(isoToDisplay(iso));
      onChange(iso);
    }
  }

  return (
    <div className="relative flex items-center">
      <input
        id={id}
        type="text"
        inputMode="numeric"
        placeholder="dd/mm/yyyy"
        value={display}
        onChange={handleTextChange}
        onBlur={handleBlur}
        disabled={disabled}
        required={required}
        className={clsx("pr-8", className)}
      />
      {/* Hidden native date input driven by the calendar icon */}
      <input
        ref={hiddenRef}
        type="date"
        tabIndex={-1}
        aria-hidden="true"
        value={value}
        min={min}
        max={max}
        onChange={handleHiddenChange}
        className="sr-only absolute inset-0 w-full opacity-0 pointer-events-none"
      />
      {/* Calendar icon — clicking opens the hidden picker */}
      <button
        type="button"
        tabIndex={-1}
        disabled={disabled}
        aria-label="Open date picker"
        onClick={() => hiddenRef.current?.showPicker()}
        className="absolute right-2 text-gray-400 hover:text-gray-600 transition-colors disabled:opacity-40"
      >
        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <rect x="3" y="4" width="18" height="18" rx="2" ry="2" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
          <line x1="16" y1="2" x2="16" y2="6" strokeWidth="2" strokeLinecap="round" />
          <line x1="8" y1="2" x2="8" y2="6" strokeWidth="2" strokeLinecap="round" />
          <line x1="3" y1="10" x2="21" y2="10" strokeWidth="2" strokeLinecap="round" />
        </svg>
      </button>
    </div>
  );
}
