"use client";

import { useEffect, useRef, useState } from "react";
import { isOwnerRole } from "@enode/core/auth/role";
import { useCurrentUser } from "@enode/core/current-user/hooks";
import type { StationLimitHolder } from "@enode/core/device-session/station-limit";
import type { TranslateFn } from "@enode/core/translations/hooks";
import { useTranslation } from "@enode/core/translations/hooks";
import { ConfirmDialog } from "@enode/ui/confirm-dialog";
import { toast } from "@enode/ui/feedback/toast-store";
import { presentError } from "@enode/ui/feedback/use-error-presenter";
import { stationLastUsedLine } from "@enode/ui/station-limit-sheet";
import {
  cancelTakeTodayStation,
  reportTodayStationOutcome,
  takeTodayStationFrom,
  undoTodayStationTake,
  useTodayStationState,
  type StationTake,
  type StationTakeUndoOutcome,
} from "./use-today-station";

// "Take 1 from …" never acts on one tap: the station-limit sheet and the
// feedback-station card only ask (`askTakeTodayStation`); this one dialog,
// mounted once on Today, says what the take does and runs it. A done take is
// confirmed in a toast with Undo (the owner's only).

/** How long the toast after a take offers Undo. */
const UNDO_TOAST_MS = 8_000;

/** The words of the take confirmation. */
export interface TakeConfirmText {
  title: string;
  /** "Last used today 12:40" / "Last used 28 Oct, 12:40"; null while unknown. */
  lastUsed: string | null;
  /** What the other device loses. */
  consequence: string;
}

/**
 * The take confirmation's words for one holder: the question, when that
 * device was last used (with the date unless today, so an old device never
 * reads as in use today) and what it loses.
 */
export function takeConfirmText(
  holder: StationLimitHolder,
  t: TranslateFn,
  locale: string,
  now: number = Date.now(),
): TakeConfirmText {
  const device = holder.deviceName;
  return {
    title: t("Take 1 training station from {device}?", { device }),
    lastUsed:
      holder.lastUsedAt == null
        ? null
        : stationLastUsedLine(holder.lastUsedAt, t, locale, now),
    consequence: t("{device} can then save one training less.", { device }),
  };
}

/** Tell the user what an Undo of a take ended in. */
function reportUndo(outcome: StationTakeUndoOutcome, deviceName: string, t: TranslateFn) {
  switch (outcome.kind) {
    case "givenBack":
      toast.success(t("Gave the training station back to {device}.", { device: deviceName }));
      return;
    case "inUse":
      toast.info(t("Finish the training to free a station."));
      return;
    case "nothingToGive":
      toast.info(t("This device has no training station to give back."));
      return;
    case "network":
      toast.info(t("Couldn't reach the server. Try again in a moment."));
      return;
    case "failed":
      presentError(outcome.error, t);
  }
}

/**
 * The confirmation of "Take 1 from …" — "Take 1 training station from
 * {device}?", when it was last used, "{device} can then save one training
 * less.", **Take 1** / **Cancel**. Confirmed, it takes the station and says so
 * in a toast; the owner's toast offers **Undo**, which gives the station back
 * the same way (see `undoTodayStationTake`). Mount once on Today.
 *
 * @param props.runningSaving - this device's columns that save right now
 * (Undo never stops a running saving training).
 */
export function TakeStationConfirm({ runningSaving }: { runningSaving: number }) {
  const { t, locale } = useTranslation();
  const { takeAsk } = useTodayStationState();
  const isOwner = isOwnerRole(useCurrentUser()?.role);
  const [busy, setBusy] = useState(false);
  // Read when Undo is tapped, seconds after the toast was made.
  const runningSavingRef = useRef(runningSaving);
  useEffect(() => {
    runningSavingRef.current = runningSaving;
  }, [runningSaving]);

  function offerUndo(take: StationTake, deviceName: string) {
    if (!isOwner) return undefined;
    return {
      actionLabel: t("Undo"),
      onAction: () =>
        void undoTodayStationTake(take, runningSavingRef.current).then((outcome) =>
          reportUndo(outcome, deviceName, t),
        ),
    };
  }

  async function take(holder: StationLimitHolder) {
    setBusy(true);
    try {
      const outcome = await takeTodayStationFrom(holder);
      if (outcome.kind !== "taken") {
        reportTodayStationOutcome(outcome, t);
        return;
      }
      toast.success(
        t("Took 1 training station from {device}.", { device: outcome.deviceName }),
        {
          durationMs: UNDO_TOAST_MS,
          ...(outcome.take ? offerUndo(outcome.take, outcome.deviceName) : undefined),
        },
      );
    } finally {
      setBusy(false);
      cancelTakeTodayStation();
    }
  }

  const text = takeAsk ? takeConfirmText(takeAsk, t, locale) : null;
  return (
    <ConfirmDialog
      open={takeAsk != null}
      title={text?.title ?? ""}
      message={
        text && (
          <>
            {text.lastUsed && <span className="block">{text.lastUsed}</span>}
            <span className="block">{text.consequence}</span>
          </>
        )
      }
      confirmLabel={t("Take 1")}
      cancelLabel={t("Cancel")}
      busy={busy}
      onConfirm={() => {
        if (takeAsk && !busy) void take(takeAsk);
      }}
      onCancel={() => {
        if (!busy) cancelTakeTodayStation();
      }}
    />
  );
}
