"use client";

import { useEffect, useMemo, useState } from "react";
import { fetchPlanUsage, type PlanUsage } from "@enode/core/api/plan-usage";
import { isAthleteRole, isOwnerRole, userHasPrivilege } from "@enode/core/auth/role";
import { usePrivilegeAccess } from "@enode/core/auth/use-privilege";
import { useCurrentUser } from "@enode/core/current-user/hooks";
import { currentUserStatus, refreshCurrentUser } from "@enode/core/current-user/store";
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 } from "@enode/core/plan/words";
import { loadUsers } from "@enode/core/users/store";
import { useUsers } from "@enode/core/users/hooks";
import { useStoreState } from "@enode/core/store-kit/hooks";
import { useTranslation } from "@enode/core/translations/hooks";
import { RequireData } from "@enode/ui/feedback/require-data";
import { openSupportReport } from "@enode/ui/feedback/support-report-store";
import { ArrowUpRightSquareIcon, DevicesFillIcon, PersonFillIcon } from "@enode/ui/icons";
import { ChevronRightIcon } from "@enode/ui/settings/icons";
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 { cloudStorageAccess } from "@enode/ui/settings/storage-access";
import { CONTACT_SALES_URL, PLANS_URL } from "../../../components/paywall/links";
import { countNotInPlan } from "./not-in-plan";
import { openPaywallLink } from "../../../components/paywall/paywall-atoms";

function formatDate(date: Date, locale: string): string {
  return date.toLocaleDateString(locale, {
    day: "numeric",
    month: "short",
    year: "numeric",
  });
}



function Skeleton() {
  return (
    <div className="flex max-w-2xl flex-col gap-4" aria-hidden>
      <div className="h-7 w-48 animate-pulse rounded-md bg-surface-base-muted" />
      <div className="h-4 w-64 animate-pulse rounded-md bg-surface-base-muted" />
      <div className="h-10 w-full animate-pulse rounded-md bg-surface-base-muted" />
      <div className="h-10 w-full animate-pulse rounded-md bg-surface-base-muted" />
    </div>
  );
}

/** Placeholder rows for the Usage card while its numbers load (no figures until then). */
function UsageSkeleton() {
  return (
    <div className="flex flex-col gap-4 px-4 py-4" aria-hidden>
      {[0, 1].map((i) => (
        <div key={i} className="flex flex-col gap-2">
          <div className="flex items-center justify-between gap-3">
            <div className="h-4 w-40 animate-pulse rounded-md bg-surface-base-muted" />
            <div className="h-4 w-12 animate-pulse rounded-md bg-surface-base-muted" />
          </div>
          <div className="h-1.5 w-full animate-pulse rounded-full bg-surface-base-muted" />
        </div>
      ))}
    </div>
  );
}

function TermLine({ term }: { term: PlanTermLine }) {
  const { t, locale } = useTranslation();
  const muted = "body-normal text-foreground-muted";
  if (term.kind === "noEnd") {
    return <p className={muted}>{t("No end date")}</p>;
  }
  if (term.kind === "ends") {
    return (
      <p
        className={`body-normal ${term.warning ? "text-feedback-warning" : "text-foreground-muted"}`}
      >
        {t("Ends on {date}", { date: formatDate(term.date, locale) })}
      </p>
    );
  }
  const date = formatDate(term.date, locale);
  if (term.store === "web") {
    return (
      <p className={muted}>
        {t("Renews on {date}", { date })}
        {" · "}
        <a className="underline" href={CONTACT_SALES_URL}>
          {t("Contact sales")}
        </a>
      </p>
    );
  }
  const storeName = term.store === "appStore" ? t("App Store") : t("Google Play");
  return (
    <p className={muted}>
      {t("Renews on {date}", { date })}
      {" · "}
      {storeName}
      {term.manageUrl ? (
        <>
          {" · "}
          <a
            className="inline-flex items-center gap-1 underline"
            href={term.manageUrl}
            target="_blank"
            rel="noopener noreferrer"
          >
            {t("Manage")}
            <ArrowUpRightSquareIcon className="size-4" />
          </a>
        </>
      ) : null}
    </p>
  );
}

/** One usage line: icon, label, "x of y" value, optional bar, links to the page that lists the details. */
function UsageRow({
  icon,
  label,
  sublabel,
  used,
  limit,
  value,
  href,
}: {
  icon: React.ReactNode;
  label: string;
  sublabel?: string;
  used: number;
  limit: number | null;
  value: string;
  href: string;
}) {
  const pct = limit && limit > 0 ? Math.min(100, Math.round((used / limit) * 100)) : null;
  return (
    <a
      href={href}
      className="flex items-center gap-3 px-4 py-3 transition-colors hover:bg-surface-base-muted"
    >
      <span
        aria-hidden="true"
        className="flex size-6 shrink-0 items-center justify-center text-foreground-default [&>svg]:size-5"
      >
        {icon}
      </span>
      <span className="min-w-0 flex-1">
        <span className="flex items-baseline justify-between gap-3">
          <span className="body-prominent text-foreground-default">{label}</span>
          <span className="body-normal whitespace-nowrap text-foreground-muted">{value}</span>
        </span>
        {pct != null ? (
          <span
            role="progressbar"
            aria-label={label}
            aria-valuemin={0}
            aria-valuemax={limit ?? undefined}
            aria-valuenow={used}
            className="mt-2 block h-1.5 overflow-hidden rounded-full bg-surface-base-muted"
          >
            <span
              className="block h-full min-w-[2px] rounded-full bg-foreground-platinum-green-bright"
              style={{ width: `${pct}%` }}
            />
          </span>
        ) : null}
        {sublabel ? (
          <span className="body-small mt-1.5 block text-foreground-muted">{sublabel}</span>
        ) : null}
      </span>
      <ChevronRightIcon className="size-4 shrink-0 text-foreground-muted" />
    </a>
  );
}

/**
 * Body of the Plan & usage page: plan name and term, usage meters, included
 * and missing features, and the plan actions. Only for users who may read the
 * plan; everyone else sees a calm note.
 */
export function PlanView() {
  const { t } = useTranslation();
  const access = usePrivilegeAccess("readLicense");
  const user = useCurrentUser();
  const userState = useStoreState(currentUserStatus);
  // The server's own count (GET /user_licenses/usage); the session-weight sum
  // below only stands in when that route fails (older server, error).
  const [usageRead, setUsageRead] = useState<
    { kind: "pending" } | { kind: "ready"; usage: PlanUsage } | { kind: "unavailable" }
  >({ kind: "pending" });
  const [usageReload, setUsageReload] = useState(0);
  const mayRead = access === "granted";
  useEffect(() => {
    if (!mayRead) return;
    let active = true;
    fetchPlanUsage().then(
      (usage) => {
        if (active) setUsageRead({ kind: "ready", usage });
      },
      () => {
        if (active) setUsageRead({ kind: "unavailable" });
      },
    );
    return () => {
      active = false;
    };
  }, [mayRead, usageReload]);
  const { sessions, state: sessionsState } = useDeviceSessions();
  const { users, state: usersState } = useUsers({ includeArchived: true });
  const placeRule = usePlaceDefinition();
  const licence = user?.license ?? null;

  const term = useMemo(
    () => (licence ? planTermLine(licence, new Date()) : null),
    [licence],
  );
  const features = planFeatureWords(licence?.privilegeKeys ?? user?.privilegeKeys);

  if (access === "denied") {
    const org = user?.organisation?.name?.trim();
    return (
      <p className="body-normal max-w-2xl text-foreground-muted">
        {org
          ? t("The owner of {organisation} manages the plan.", {
              organisation: org,
            })
          : t("The owner of your organisation manages the plan.")}
      </p>
    );
  }

  const retry = () => {
    void refreshCurrentUser({ force: true });
    void loadDeviceSession().catch(() => {});
    loadUsers({ force: true });
    setUsageRead({ kind: "pending" });
    setUsageReload((n) => n + 1);
  };

  const usage = usageRead.kind === "ready" ? usageRead.usage : null;
  const stationsUsed =
    usage?.stations.used ?? sessions.reduce((sum, s) => sum + (s.weight ?? 0), 0);
  const stationsLimit = usage
    ? (usage.stations.total ?? licence?.deviceLimit ?? null)
    : (licence?.deviceLimit ?? null);

  const usersUsed = usage?.people.active ?? licence?.activeUserCount ?? 0;
  const usersLimit = usage
    ? (usage.people.limit ?? licence?.activeUserLimit ?? null)
    : (licence?.activeUserLimit ?? null);
  const notInPlan = usage ? usage.people.notInPlan : countNotInPlan(users);

  const cloudAccess = cloudStorageAccess({
    role: isOwnerRole(user?.role) ? "owner" : isAthleteRole(user?.role) ? "athlete" : "coach",
    hasWriteCloudStorage: userHasPrivilege(user, "writeCloudStorage"),
    totalVideoStorageBytes: licence?.totalVideoStorage ?? 0,
  });
  const usageValue = (used: number, limit: number | null) =>
    limit == null ? String(used) : t("{used} of {limit}", { used, limit });
  const organisation = user?.organisation?.name?.trim() || null;

  const body = licence ? (
    <SettingsPage>
      <PlanCard
        planName={licence.name || t("Enode Pro")}
        term={term ? <TermLine term={term} /> : null}
      />

      <SettingsCardGroup header={t("Usage")} findId="acc-plan.usage">
        <RequireData
          requirements={[
            {
              state: sessionsState,
              satisfied:
                usage != null ||
                (usageRead.kind === "unavailable" &&
                  (sessionsState.status === "ready" || sessionsState.status === "refreshing")),
              label: t("your training stations"),
            },
            { state: usersState, satisfied: usage != null || users != null, label: t("your athletes and coaches") },
          ]}
          onRetry={retry}
          loading={<UsageSkeleton />}
        >
          <UsageRow
            icon={<PersonFillIcon />}
            label={t("Athletes & coaches")}
            used={usersUsed}
            limit={usersLimit}
            value={usageValue(usersUsed, usersLimit)}
            sublabel={
              notInPlan > 0
                ? // The place rule is a full sentence, so the count follows
                  // as a second one rather than a " · " fragment.
                  `${placeRule} ${t(
                    "{n, plural, one {# person isn't in the plan.} other {# people aren't in the plan.}}",
                    { n: notInPlan },
                  )}`
                : placeRule
            }
            href="/dashboard/users"
          />
          <NavRowDivider inset="none" />
          <UsageRow
            icon={<DevicesFillIcon />}
            label={t("Training stations")}
            used={stationsUsed}
            limit={stationsLimit}
            value={usageValue(stationsUsed, stationsLimit)}
            sublabel={t("Tablets and phones that hold a station")}
            href="/dashboard/devices"
          />
        </RequireData>
      </SettingsCardGroup>

      <PlanFeatureList
        included={features.included}
        notIncluded={features.notIncluded}
        dataExportHref="/dashboard/account/data"
      />

      {cloudAccess === "manage" ? (
        <GymCloudStorageSection
          enabled
          totalBytes={licence.totalVideoStorage ?? 0}
          organisationName={organisation}
          peopleCount={licence.activeUserCount ?? null}
        />
      ) : null}

      <SettingsCardGroup>
        <NavRow
          label={t("Compare plans")}
          onPress={() => openPaywallLink(PLANS_URL)}
          trailing={<ArrowUpRightSquareIcon className="size-4" />}
          ariaDescription={t("opens enode.ai")}
          findId="acc-plan.compare"
        />
        <NavRowDivider inset="none" />
        <NavRow
          label={t("Talk to us about your plan")}
          onPress={() => openPaywallLink(CONTACT_SALES_URL)}
          trailing={<ArrowUpRightSquareIcon className="size-4" />}
          ariaDescription={t("opens your email app")}
        />
        <NavRowDivider inset="none" />
        <NavRow label={t("Report a problem")} onPress={() => openSupportReport()} />
      </SettingsCardGroup>
    </SettingsPage>
  ) : null;

  return (
    <RequireData
      requirements={[
        { state: userState, satisfied: !!licence, label: t("your plan") },
      ]}
      onRetry={retry}
      showStaleHint
      loading={<Skeleton />}
    >
      {body}
    </RequireData>
  );
}
