import type { FC } from "react";
import { useTranslation } from "@/i18n/provider.js";
import { parseYyyymmdd } from "./dateRange.js";
import "./DayTabs.scss";

export interface DaySelectProps {
  selectedDate: string;
  availableDates: string[];
  locale: string;
  onNavigate: (date: string) => void;
  /**
   * Optional caption shown above the dropdown (e.g. 'Дата рейса' on the
   * flight details page). Angular renders this via day-tabs' `caption`
   * input. Omit for search pages where no caption is wanted.
   */
  captionKey?: string;
}

function formatLabel(date: string, locale: string): string {
  const d = parseYyyymmdd(date);
  return new Intl.DateTimeFormat(locale, {
    weekday: "short",
    month: "short",
    day: "numeric",
  }).format(d);
}

export const DaySelect: FC<DaySelectProps> = ({
  selectedDate,
  availableDates,
  locale,
  onNavigate,
  captionKey,
}) => {
  const { t } = useTranslation();
  // No data → don't render an empty dropdown that just adds visual
  // noise on mobile. Angular hides the date picker when the calendar
  // API hasn't returned any usable days for this view.
  if (availableDates.length === 0) return null;
  return (
    <div className="day-select-wrap">
      {captionKey && (
        <label className="day-select-wrap__caption">{t(captionKey)}</label>
      )}
      <select
        className="day-select"
        data-testid="day-select"
        value={selectedDate}
        onChange={(e) => onNavigate(e.target.value)}
      >
        {availableDates.map((date) => (
          <option key={date} value={date}>
            {formatLabel(date, locale)}
          </option>
        ))}
      </select>
    </div>
  );
};
