import { type FC, useEffect, useRef, useState } from "react";
import { format } from "date-fns";
import { useTranslation } from "@/i18n/provider.js";
import type { ISimpleFlight } from "../../types.js";
import { ShareButton } from "./ShareButton.js";

export interface LastUpdateProps {
  flight: ISimpleFlight;
  locale: string;
}

function formatStamp(d: Date): string {
  return format(d, "HH:mm dd.MM.yyyy");
}

/**
 * Renders the "Последнее обновление: HH:mm DD.MM.YYYY" stamp + share
 * button. Angular sets `flight.lastUpdate = new Date()` inside
 * `populate.logic.ts` when a flight is hydrated, so the stamp reflects
 * when the client received the data — not the API record's mutation
 * timestamp. We mirror that here: capture `Date.now()` the first time we
 * see a given flight.id, then re-capture whenever the id changes.
 */
export const LastUpdate: FC<LastUpdateProps> = ({ flight, locale }) => {
  const { t } = useTranslation();
  const [loadedAt, setLoadedAt] = useState<Date>(() => new Date());
  const seenFlightIdRef = useRef<string | null>(null);

  useEffect(() => {
    if (seenFlightIdRef.current !== flight.id) {
      seenFlightIdRef.current = flight.id;
      setLoadedAt(new Date());
    }
  }, [flight.id]);

  const timestamp = formatStamp(loadedAt);
  const shareUrl = typeof window !== "undefined" ? window.location.href : "";

  return (
    <div className="last-update">
      <ShareButton url={shareUrl} locale={locale} />
      <span className="last-update__description">
        <span>{t("SHARED.LAST-UPDATE")}:</span>
        <span className="last-update__time" data-testid="last-update-timestamp">
          &nbsp;{timestamp}
        </span>
      </span>
    </div>
  );
};
