"use client";

import { useRouter } from "next/navigation";

interface StopsDatePickerProps {
  value: Date;
}

/**
 * Format a Date as the `YYYY-MM-DD` value used by `<input type="date">`.
 *
 * Uses local-time components (not `toISOString()`) so the picker doesn't
 * snap to the day before/after for users in a non-UTC timezone — a date
 * picker where selecting "today" in the user's browser unexpectedly
 * changes the URL by a day is a common footgun.
 */
function toInputValue(d: Date): string {
  const yyyy = d.getFullYear();
  const mm = String(d.getMonth() + 1).padStart(2, "0");
  const dd = String(d.getDate()).padStart(2, "0");
  return `${yyyy}-${mm}-${dd}`;
}

/**
 * StopsDatePicker — native `<input type="date">` for the v2 stops list.
 *
 * Pushing a new URL on change triggers a server re-render of the page
 * with the new date. The page's `searchParams.date` is the source of
 * truth; this component is purely an input control.
 *
 * The pill is sized at 56px to match the rest of the v2 action bar
 * (matching OrdersFilterButton).
 */
export function StopsDatePicker({ value }: StopsDatePickerProps) {
  const router = useRouter();
  return (
    <label
      className="rounded-xl flex items-center gap-2"
      style={{
        minHeight: "56px",
        padding: "0 16px",
        backgroundColor: "var(--color-surface-2)",
        fontWeight: 600,
        letterSpacing: "0.02em",
      }}
    >
      <span className="text-label" style={{ color: "var(--color-text-muted)" }}>
        Date
      </span>
      <input
        type="date"
        value={toInputValue(value)}
        onChange={(e) => {
          const newDate = e.target.value;
          if (!newDate) return;
          router.push(`/admin/v2/stops?date=${newDate}`);
        }}
        className="bg-transparent border-0 outline-none focus-visible:outline-2 focus-visible:outline-[var(--color-accent)] focus-visible:outline-offset-2"
        style={{
          fontSize: "15px",
          fontWeight: 600,
          color: "var(--color-text)",
        }}
        // Restore keyboard-only focus ring; mouse users keep the
        // minimal look.
        onFocus={(e) => {
          e.currentTarget.style.outline = "2px solid var(--color-accent)";
          e.currentTarget.style.outlineOffset = "2px";
        }}
        onBlur={(e) => {
          e.currentTarget.style.outline = "none";
          e.currentTarget.style.outlineOffset = "0";
        }}
      />
    </label>
  );
}

export default StopsDatePicker;
