"use client";

import { useState } from "react";
import { isOwnerRole } from "@enode/core/auth/role";
import { useHasPrivilege } from "@enode/core/auth/use-privilege";
import { useCurrentUser } from "@enode/core/current-user/hooks";
import type { StationLimitHolder } from "@enode/core/device-session/station-limit";
import { useTranslation, type TranslateFn } from "@enode/core/translations/hooks";
import { Button } from "@enode/ui/button";
import { DataEmptyState } from "@enode/ui/feedback/data-empty-state";
import { TabletPulseIcon } from "@enode/ui/icons";
import { FeedbackStationSkeleton } from "./feedback-station-skeleton";
import { allStationsHeld } from "./this-device-stations";
import {
  askTakeTodayStation,
  mayTakeStation,
  reportTodayStationOutcome,
  retryTodayStation,
  useStationFacts,
  useTodayStationState,
  type TodayStationRetryOutcome,
} from "./use-today-station";

// The card reads who holds the stations fresh when it mounts (the plan
// count may be at most this old); it never asks for a station by itself.
const BANNER_FACTS_MAX_AGE_MS = 2_000;

/** Which station action the feedback-station card offers. */
export type StationBannerView =
  /** A station is free (or the plan size is unknown): use one. */
  | { kind: "use" }
  /** Every station is held, some by other devices: take one from them (the owner). */
  | { kind: "take"; holders: StationLimitHolder[] }
  /** As `take`, for anyone but the owner: ask the owner instead. */
  | { kind: "askOwner"; holders: StationLimitHolder[] }
  /** Every station is held by this device (its training stations). */
  | { kind: "ownColumns" };

/**
 * Which station action the feedback-station card offers, from who holds the
 * stations — known up front, so a full plan offers what will work instead of
 * a request that is refused. "Held" counts every holder — this device's own
 * stations too, so a feedback station on a device that already holds the last
 * free station is not offered one that isn't there. An unknown plan size
 * never counts as held: then the card offers "Use a training station", and a
 * refusal opens the station-limit sheet.
 *
 * @param canTake - {@link mayTakeStation}.
 */
export function stationBannerView(input: {
  total: number;
  ownWeight: number | null;
  others: readonly StationLimitHolder[];
  canTake: boolean;
}): StationBannerView {
  const own: StationLimitHolder = {
    sessionId: "",
    deviceName: "",
    weight: input.ownWeight ?? 0,
  };
  const held = allStationsHeld({ total: input.total, holders: [own, ...input.others] });
  if (held !== true) return { kind: "use" };
  if (input.others.length === 0) return { kind: "ownColumns" };
  const holders = [...input.others];
  return input.canTake ? { kind: "take", holders } : { kind: "askOwner", holders };
}

/**
 * The line for anyone who may not take a station while all are held: only
 * the owner moves training stations, so ask them — by organisation name when
 * it is known.
 */
export function askOwnerLine(organisation: string | null, t: TranslateFn): string {
  return organisation
    ? t("Only the owner can move training stations. Ask the owner of {org} for one.", {
        org: organisation,
      })
    : t("Only the owner can move training stations. Ask the owner for one.");
}

/**
 * The card of a feedback station (a column that can't save; it shows no
 * schedule), floating over a static skeleton of a Feedback training
 * (DataEmptyState's showcase layout, like the portal's empty Insights tabs):
 * "Train with live feedback" / "Trainings at a feedback station aren't
 * saved." with **Start feedback training**, buttons stacked. The left-most feedback station also offers a station
 * — "Use a training station" when one is free or the plan size is unknown,
 * "Take 1 from …" when other devices hold them all (the owner; it asks for a
 * confirmation first, see `TakeStationConfirm`), else a line saying why
 * there is none and whom to ask — since a station got here lands in it
 * (stations fill from the left).
 *
 * @param props.offerStation - this is the left-most feedback station.
 */
export function NoTrainingStationCard({
  onFeedbackTraining,
  offerStation,
}: {
  onFeedbackTraining: () => void;
  offerStation: boolean;
}) {
  const { t } = useTranslation();
  const user = useCurrentUser();
  const canWrite = useHasPrivilege("writeDeviceSession");
  const [busy, setBusy] = useState(false);
  const { takeNotAllowed } = useTodayStationState();
  const { total, ownWeight, others } = useStationFacts({
    maxAgeMs: BANNER_FACTS_MAX_AGE_MS,
  });
  const view = stationBannerView({
    total,
    ownWeight,
    others,
    canTake: mayTakeStation({
      isOwner: isOwnerRole(user?.role),
      canWriteDeviceSession: canWrite,
      takeNotAllowed,
    }),
  });
  const organisation = user?.organisation?.name?.trim() || null;

  async function run(action: () => Promise<TodayStationRetryOutcome>) {
    setBusy(true);
    try {
      reportTodayStationOutcome(await action(), t);
    } finally {
      setBusy(false);
    }
  }

  return (
    <section aria-label={t("Feedback station")}>
      <DataEmptyState
        mock={<FeedbackStationSkeleton />}
        icon={
          <span className="flex size-16 items-center justify-center rounded-2xl bg-foreground-red-orange/12 text-brand-red-orange">
            <TabletPulseIcon className="size-8" />
          </span>
        }
        title={t("Train with live feedback")}
        description={t("Trainings at a feedback station aren't saved.")}
        // The buttons stack, full width: a feedback station's column is
        // narrow, and "Take 1 from …" may come once per device.
        action={
          <div className="flex w-full flex-col gap-2">
            <Button variant="primary" size="small" onClick={onFeedbackTraining}>
              {t("Start feedback training")}
            </Button>
            {offerStation && view.kind === "use" && (
              <Button
                variant="neutral"
                size="small"
                busy={busy}
                onClick={() => void run(retryTodayStation)}
              >
                {t("Use a training station")}
              </Button>
            )}
            {offerStation &&
              view.kind === "take" &&
              view.holders.map((holder) => (
                <Button
                  key={holder.sessionId}
                  variant="neutral"
                  size="small"
                  onClick={() => askTakeTodayStation(holder)}
                >
                  {t("Take 1 from {deviceName}", { deviceName: holder.deviceName })}
                </Button>
              ))}
          </div>
        }
      >
        {offerStation && view.kind !== "use" && (
          <p className="body-small text-foreground-muted">
            <HeldLine view={view} total={total} organisation={organisation} />
          </p>
        )}
      </DataEmptyState>
    </section>
  );
}

/** Why no free station is offered: whole sentences, one per fact. */
function HeldLine({
  view,
  total,
  organisation,
}: {
  view: Exclude<StationBannerView, { kind: "use" }>;
  total: number;
  organisation: string | null;
}) {
  const { t } = useTranslation();
  if (view.kind === "ownColumns") {
    return (
      <>
        {t(
          "{total, plural, one {The plan's training station is on this device.} other {All # training stations of the plan are on this device.}}",
          { total },
        )}
      </>
    );
  }
  const single =
    view.holders.length === 1 && view.holders[0].weight >= total ? view.holders[0] : null;
  const held = single
    ? t(
        "{deviceName} {total, plural, one {holds the training station} =2 {holds both training stations} other {holds all # training stations}}.",
        { deviceName: single.deviceName, total },
      )
    : t(
        "{total, plural, one {The training station is in use.} =2 {Both training stations are in use.} other {All # training stations are in use.}}",
        { total },
      );
  if (view.kind === "take") return <>{held}</>;
  return (
    <>
      <span>{held}</span> <span>{askOwnerLine(organisation, t)}</span>
    </>
  );
}
