import type { FC } from "react";
import { parseISO, format, isValid } 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 getUpdated(flight: ISimpleFlight): string | undefined {
  const leg = flight.routeType === "Direct" ? flight.leg : flight.legs[0];
  return leg?.updated;
}

function formatUpdated(updated: string | undefined): string {
  if (!updated) return "";
  const d = parseISO(updated);
  if (!isValid(d)) return "";
  return format(d, "HH:mm dd.MM.yyyy");
}

export const LastUpdate: FC<LastUpdateProps> = ({ flight, locale }) => {
  const { t } = useTranslation();
  const timestamp = formatUpdated(getUpdated(flight));
  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>
  );
};
