"use client";

import { useEffect, useMemo, useState } from "react";
import {
  isAthleteRole,
  isOwnerRole,
  userHasPrivilege,
} from "@enode/core/auth/role";
import { useCurrentUser } from "@enode/core/current-user/hooks";
import {
  currentUserStatus,
  loadCurrentUser,
} from "@enode/core/current-user/store";
import {
  fetchPlanUsage,
  type PlanUsage,
  type PlanUsageStationHolder,
} from "@enode/core/api/plan-usage";
import { useDeviceSessions } from "@enode/core/device-session/hooks";
import { loadDeviceSession } from "@enode/core/device-session/store";
import {
  planFeatureWords,
  planTermLine,
  type PlanTermLine,
} from "@enode/core/plan/plan-summary";
import { usePlaceDefinition, useStationDefinition } from "@enode/core/plan/words";
import { useStoreState } from "@enode/core/store-kit/hooks";
import { useTranslation, type TranslateFn } from "@enode/core/translations/hooks";
import { AccountRoomFrame } from "@enode/ui/account/account-room-view";
import { GymCloudStorageSection } from "@enode/ui/plan/gym-cloud-storage";
import { PlanCard } from "@enode/ui/plan/plan-card";
import { PlanFeatureList } from "@enode/ui/plan/plan-features";
import { NavRow, NavRowDivider } from "@enode/ui/settings/nav-row";
import { SettingsCardGroup, SettingsPage } from "@enode/ui/settings/settings-card-group";
import { isUnlimitedStationLimit } from "./account-view-words";
import { cloudStorageAccess } from "@enode/ui/settings/storage-access";

// same as apps/portal/src/components/paywall/links.ts
const PLANS_URL = "https://enode.ai/pages/pricing";
const CONTACT_SALES_URL = "mailto:sales@enode.ai";

/** What the app knows about the plan's training stations. */
export interface TrainingStationUsage {
  /** Stations held right now. */
  used: number;
  /** Stations in the plan; null when unknown or unlimited. */
  limit: number | null;
  /** Devices holding stations (server count); null when the usage route is unavailable. */
  holders: readonly PlanUsageStationHolder[] | null;
  /** Own device sessions; null until loaded. */
  sessionsCount: number | null;
  /** Whether `used` is known: only when the server's usage route answered. */
  loaded: boolean;
  /** Whether the usage read has finished (answered or unavailable). */
  settled: boolean;
  /** Places as the server counts them; null when the usage route did not answer. */
  people: PlanUsage["people"] | null;
}

/** Where the station count comes from: the server's usage route, else the old session sum. */
export type PlanUsageRead =
  | { kind: "pending" }
  | { kind: "ready"; usage: PlanUsage }
  | { kind: "unavailable" };

/**
 * Pure merge of the usage sources. Uses `GET /user_licenses/usage` (the count
 * the server grants with, same as the portal). When that route is unavailable
 * (athlete, older server, error) the app's own session list is incomplete (it
 * only sees this device), so `used` is NOT computed from it: `loaded` stays
 * false, `used` is 0 and only the plan total (`licenceLimit`) is known.
 */
export function mergeStationUsage(
  read: PlanUsageRead,
  sessions: readonly unknown[],
  sessionsLoaded: boolean,
  licenceLimit: number | null,
): TrainingStationUsage {
  const sessionsCount = sessionsLoaded ? sessions.length : null;
  if (read.kind === "ready") {
    return {
      used: read.usage.stations.used,
      limit: read.usage.stations.total ?? licenceLimit,
      holders: read.usage.stations.holders,
      sessionsCount,
      loaded: true,
      settled: true,
      people: read.usage.people,
    };
  }
  return {
    used: 0,
    limit: licenceLimit,
    holders: null,
    sessionsCount,
    loaded: false,
    settled: read.kind === "unavailable",
    people: null,
  };
}

// One shared read for the Account header, Plan & usage and Devices; re-read
// when older than this.
const USAGE_FRESH_MS = 30_000;
let usageCache: { at: number; read: Promise<PlanUsageRead> } | null = null;

function readPlanUsage(maxAgeMs: number = USAGE_FRESH_MS): Promise<PlanUsageRead> {
  if (usageCache && Date.now() - usageCache.at < maxAgeMs) {
    return usageCache.read;
  }
  const read = fetchPlanUsage().then(
    (usage): PlanUsageRead => ({ kind: "ready", usage }),
    (): PlanUsageRead => ({ kind: "unavailable" }),
  );
  usageCache = { at: Date.now(), read };
  return read;
}

/** Drop the shared usage read so the next mount fetches again (Try again, tests). */
export function resetPlanUsageCache(): void {
  usageCache = null;
}

/**
 * Training stations in use against the plan limit, as the server counts them
 * (`GET /user_licenses/usage`, shared with the portal). Athletes never ask the
 * route (it answers 403); for them, and on servers without it, only the plan
 * total is shown. See {@link mergeStationUsage}.
 *
 * @param maxAgeMs - how old the shared read may be (default 30 s); a small
 * value reads fresh when the caller mounts.
 */
export function useTrainingStationUsage(
  options: { maxAgeMs?: number } = {},
): TrainingStationUsage {
  const { maxAgeMs } = options;
  const { sessions, state } = useDeviceSessions();
  const user = useCurrentUser();
  const limit = user?.license?.deviceLimit ?? null;
  const mayRead = user != null && !isAthleteRole(user.role);
  const [read, setRead] = useState<PlanUsageRead>({ kind: "pending" });

  useEffect(() => {
    if (!mayRead) return;
    let active = true;
    void readPlanUsage(maxAgeMs).then((next) => {
      if (active) setRead(next);
    });
    return () => {
      active = false;
    };
  }, [mayRead, maxAgeMs]);

  return mergeStationUsage(
    mayRead ? read : { kind: "unavailable" },
    sessions,
    state.hasData,
    limit,
  );
}

/**
 * Places in use against the plan's places, like the portal's Plan & usage:
 * the server's usage count when it answered, else the licence's own counts.
 */
export function planPlaces(
  people: PlanUsage["people"] | null,
  licence: { activeUserCount?: number; activeUserLimit?: number } | null,
): { used: number; limit: number | null } {
  if (people) {
    return { used: people.active, limit: people.limit ?? licence?.activeUserLimit ?? null };
  }
  return { used: licence?.activeUserCount ?? 0, limit: licence?.activeUserLimit ?? null };
}

/**
 * The training-stations value: "n of m in use" once the server's count is
 * known; while it loads "Loading…"; without it (route unavailable) only the
 * plan total, never a count of its own.
 */
export function stationsValue(t: TranslateFn, usage: TrainingStationUsage): string {
  if (usage.loaded) {
    // An unlimited plan (Enterprise, limit > 100) shows the count alone (17.11.26)
    return usage.limit == null || isUnlimitedStationLimit(usage.limit)
      ? t("{used} in use", { used: usage.used })
      : t("{used} of {limit} in use", { used: usage.used, limit: usage.limit });
  }
  if (!usage.settled) return t("Loading…");
  if (isUnlimitedStationLimit(usage.limit)) return t("Unlimited");
  return usage.limit != null ? String(usage.limit) : "—";
}

function useTermText(term: PlanTermLine | null): string | null {
  const { t } = useTranslation();
  if (!term) return null;
  if (term.kind === "noEnd") return t("No end date");
  const date = term.date.toLocaleDateString();
  return term.kind === "renews"
    ? t("Renews {date}", { date })
    : t("Ends {date}", { date });
}

/**
 * Read-only "Plan & usage" drawer view for the account owner, like the
 * portal's: plan name and term, places and training stations ("n of m in
 * use" when known), the Included list, "Compare plans" and "Talk to us about
 * your plan". No purchase, upgrade or subscription path. Shows a loading line while the plan
 * loads and a neutral message with "Try again" when it cannot be read.
 */
export function AccountPlanView() {
  const { t } = useTranslation();
  const user = useCurrentUser();
  const userState = useStoreState(currentUserStatus);
  const usage = useTrainingStationUsage();
  const placeRule = usePlaceDefinition();
  const stationRule = useStationDefinition();
  const licence = user?.license ?? null;
  const term = useMemo(
    () => (licence ? planTermLine(licence, new Date()) : null),
    [licence],
  );
  const termText = useTermText(term);
  const cloudAccess = cloudStorageAccess({
    role: isOwnerRole(user?.role) ? "owner" : isAthleteRole(user?.role) ? "athlete" : "coach",
    hasWriteCloudStorage: userHasPrivilege(user, "writeCloudStorage"),
    totalVideoStorageBytes: licence?.totalVideoStorage ?? 0,
  });

  const failed =
    !licence && (userState.status === "error" || userState.status === "ready");
  const organisation = user?.organisation?.name?.trim() || null;
  // Same feature split as the portal's Plan & usage.
  const features = planFeatureWords(licence?.privilegeKeys ?? user?.privilegeKeys);

  let body;
  if (licence) {
    const planName = licence.name || t("Enode Pro");
    const places = planPlaces(usage.people, licence);
    body = (
      <SettingsPage>
        <PlanCard
          planName={planName}
          term={termText ? <p className="body-normal">{termText}</p> : null}
        />
        <SettingsCardGroup
          header={t("Usage")}
          footer={stationRule}
          findId="acc-plan.usage"
        >
          <NavRow
            label={t("Training stations in your plan")}
            value={stationsValue(t, usage)}
          />
          <NavRowDivider inset="none" />
          <NavRow
            label={t("Athletes & coaches")}
            value={
              places.limit == null
                ? t("{used} in use", { used: places.used })
                : t("{used} of {limit} in use", { used: places.used, limit: places.limit })
            }
            sublabel={placeRule}
          />
        </SettingsCardGroup>
        <PlanFeatureList included={features.included} notIncluded={features.notIncluded} />
        {cloudAccess === "manage" ? (
          <GymCloudStorageSection
            enabled
            totalBytes={licence.totalVideoStorage ?? 0}
            organisationName={organisation}
            peopleCount={licence.activeUserCount ?? null}
          />
        ) : null}
        {/* What the portal's Plan & usage offers. No "Manage subscription"
            until billing exists (backend P7-B17). */}
        <SettingsCardGroup>
          <NavRow
            label={t("Compare plans")}
            href={PLANS_URL}
            external
            ariaDescription={t("opens enode.ai")}
            findId="acc-plan.compare"
          />
          <NavRowDivider inset="none" />
          <NavRow
            label={t("Talk to us about your plan")}
            onPress={() => {
              // mailto: hands over to the mail app (browser and Capacitor).
              window.location.href = CONTACT_SALES_URL;
            }}
            external
            ariaDescription={t("opens your email app")}
            findId="acc-plan.contact"
          />
        </SettingsCardGroup>
      </SettingsPage>
    );
  } else if (failed) {
    body = (
      <div className="flex flex-col items-start gap-3 pt-4">
        <p className="body-normal text-foreground-muted">
          {t("Couldn't load your plan.")}
        </p>
        <button
          type="button"
          onClick={() => {
            resetPlanUsageCache();
            void loadCurrentUser({ force: true }).catch(() => {});
            void loadDeviceSession().catch(() => {});
          }}
          className="clickable-small text-foreground-default underline-offset-2 hover:underline"
        >
          {t("Try again")}
        </button>
      </div>
    );
  } else {
    body = (
      <p role="status" className="body-normal pt-4 text-foreground-muted">
        {t("Loading…")}
      </p>
    );
  }

  return <AccountRoomFrame title={t("Plan & usage")}>{body}</AccountRoomFrame>;
}
