import { i18nMessage, useGuardedNavigate } from "@govoplan/core-webui";
import { ArrowBigLeft, ArrowBigLeftDash, ArrowBigRight, ArrowBigRightDash } from "lucide-react";
import { useLocation } from "react-router-dom";
import type { CampaignVersionDetail, CampaignVersionListItem } from "../../../api/campaigns";
import { formatDateTime } from "../utils/campaignView";

type VersionLineProps = {
  version: CampaignVersionDetail | CampaignVersionListItem | null;
  versions?: CampaignVersionListItem[];
  status?: string;
  loadedAt?: string | null;
};

export default function VersionLine({ version, versions = [], status, loadedAt }: VersionLineProps) {
  const location = useLocation();
  const navigate = useGuardedNavigate();
  const sorted = versions.slice().sort((a, b) => (a.version_number ?? 0) - (b.version_number ?? 0));
  const currentIndex = version ? sorted.findIndex((item) => item.id === version.id) : -1;
  const first = currentIndex > 0 ? sorted[0] : null;
  const previous = currentIndex > 0 ? sorted[currentIndex - 1] : null;
  const next = currentIndex >= 0 && currentIndex < sorted.length - 1 ? sorted[currentIndex + 1] : null;
  const latest = currentIndex >= 0 && currentIndex < sorted.length - 1 ? sorted[sorted.length - 1] : null;
  const suffix = status ?? `Loaded ${formatDateTime(loadedAt ?? version?.updated_at)}`;

  function openVersion(target: CampaignVersionListItem) {
    const targetUrl = versionTarget(location.pathname, location.search, target.id);
    navigate(targetUrl);
  }

  return (
    <p className="mono-small version-line">
      <VersionArrow
        icon="first"
        target={first}
        fallbackLabel="i18n:govoplan-campaign.already_at_first_version.b90fad64"
        onOpen={openVersion} />
      
      <VersionArrow
        icon="previous"
        target={previous}
        fallbackLabel="i18n:govoplan-campaign.no_older_version.4355dee8"
        onOpen={openVersion} />
      
      <span>i18n:govoplan-campaign.version.2da600bf {version ? i18nMessage("i18n:govoplan-campaign.value.44b8c76f", { value0: version.version_number }) : "—"}</span>
      <VersionArrow
        icon="next"
        target={next}
        fallbackLabel="i18n:govoplan-campaign.no_newer_version.b210a41c"
        onOpen={openVersion} />
      
      <VersionArrow
        icon="latest"
        target={latest}
        fallbackLabel="i18n:govoplan-campaign.already_at_latest_version.7533bd9d"
        onOpen={openVersion} />
      
      <span className="version-line-separator">·</span>
      <span>{suffix}</span>
    </p>);

}

type VersionArrowProps = {
  icon: "first" | "previous" | "next" | "latest";
  target: CampaignVersionListItem | null;
  fallbackLabel: string;
  onOpen: (target: CampaignVersionListItem) => void;
};

function VersionArrow({ icon, target, fallbackLabel, onOpen }: VersionArrowProps) {
  const Icon = getVersionIcon(icon);
  const actionLabel = getVersionActionLabel(icon, target);

  if (!target) {
    return (
      <span className="version-arrow disabled" title={fallbackLabel} aria-label={fallbackLabel}>
        <Icon aria-hidden="true" />
      </span>);

  }

  return (
    <button
      type="button"
      className="version-arrow"
      onClick={() => onOpen(target)}
      title={actionLabel}
      aria-label={actionLabel}>
      
      <Icon aria-hidden="true" />
    </button>);

}

function getVersionIcon(icon: VersionArrowProps["icon"]) {
  switch (icon) {
    case "first":
      return ArrowBigLeftDash;
    case "previous":
      return ArrowBigLeft;
    case "next":
      return ArrowBigRight;
    case "latest":
      return ArrowBigRightDash;
  }
}

function getVersionActionLabel(icon: VersionArrowProps["icon"], target: CampaignVersionListItem | null): string {
  const versionLabel = target ? `version #${target.version_number}` : "version";
  switch (icon) {
    case "first":
      return i18nMessage("i18n:govoplan-campaign.open_first_value.ea8f5c5b", { value0: versionLabel });
    case "previous":
      return i18nMessage("i18n:govoplan-campaign.open_previous_value.e8d4794b", { value0: versionLabel });
    case "next":
      return i18nMessage("i18n:govoplan-campaign.open_next_value.1315037e", { value0: versionLabel });
    case "latest":
      return i18nMessage("i18n:govoplan-campaign.open_latest_value.40bdb320", { value0: versionLabel });
  }
}

function versionTarget(pathname: string, search: string, versionId: string): string {
  const params = new URLSearchParams(search);
  params.set("version", versionId);
  return `${pathname}?${params.toString()}`;
}
