"use client";

import type { PaymentsDashboardWallet } from "@sdp/types";
import { Loader2Icon, SparklesIcon, WalletIcon } from "lucide-react";
import { useSearchParams } from "next/navigation";
import { useCallback, useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { useDashboardWorkspace } from "@/contexts/dashboard-workspace-context";
import { useTranslations } from "@/i18n/provider";
import { usePersistedDashboardSWR } from "@/lib/dashboard-swr";
import { useDashboardUrlState } from "@/lib/dashboard-url-state";
import { getTokenAccessControlMode, hasAccessControlList } from "../access-control.utils";
import { TokenActionConfirmationDialog } from "./token-action-confirmation-dialog";
import { TokenActionForms } from "./token-action-forms";
import { TokenAuthorityModal } from "./token-authority-modal";
import { TokenControlListsSection } from "./token-control-lists-section";
import { TokenDisabledActionTooltip } from "./token-disabled-action-tooltip";
import {
  type FundManagementModalAction,
  TokenFundManagementSection,
} from "./token-fund-management-section";
import { TokenManagementHeader } from "./token-management-header";
import { TokenManagementModalShell } from "./token-management-modal-shell";
import {
  fetchTokenAuthorityWallets,
  fetchTokenManagementSupportingData,
  type TokenAuthorityWalletsData,
  type TokenManagementSupportingData,
} from "./token-management-workspace.data";
import type {
  ActionExecutionInput,
  AdminAction,
  DeployFeePayment,
  PermissionRow,
  RunActionOptions,
  TokenManagementTab,
  TokenManagementWorkspaceProps,
} from "./token-management-workspace.types";
import {
  asOptionalString,
  createInitialAllowlistForm,
  createInitialAuthorityForm,
  createInitialBurnForm,
  createInitialForceBurnForm,
  createInitialFreezeForm,
  createInitialMetadataForm,
  createInitialMintForm,
  createInitialSeizeForm,
  findWalletByWalletId,
  getBurnValidationErrors,
  getBurnValidationReason,
  getControlListCopy,
  getDefaultActionForTab,
  getDisplayedAuthorityAddress,
  getExplorerHref,
  getExtensionRows,
  getForceBurnValidationErrors,
  getForceBurnValidationReason,
  getMintValidationErrors,
  getMintValidationReason,
  getPermissionRows,
  getSeizeValidationErrors,
  getSeizeValidationReason,
  getSignerSelectionForAction,
  getTabForAction,
  getTokenActionDisabledReasons,
  isPositiveAmount,
  resolveAuthorityAddressForRole,
} from "./token-management-workspace.utils";
import { TokenOverviewSection } from "./token-overview-section";
import { TokenSettingsSection } from "./token-settings-section";
import { TokenSignerSelect } from "./token-signer-select";
import { TokenTransactionsSection } from "./token-transactions-section";
import { useTokenActionRunner } from "./use-token-action-runner";

const managementTabIds: TokenManagementTab[] = [
  "overview",
  "permissions",
  "extensions",
  "compliance",
  "metadata",
  "fund-management",
];
const TOKEN_AUTHORITY_WALLETS_CACHE_TTL_MS = 60_000;
const TOKEN_SUPPORTING_DATA_CACHE_TTL_MS = 60_000;

function isTokenManagementTab(value: string | null): value is TokenManagementTab {
  return managementTabIds.some((tab) => tab === value);
}

function getDefaultActionForActiveTab({
  tab,
  canDeployToken,
  showControlList,
  canManageTokenAdmin,
}: {
  tab: TokenManagementTab;
  canDeployToken: boolean;
  showControlList: boolean;
  canManageTokenAdmin: boolean;
}): AdminAction | null {
  if (tab === "fund-management" && canDeployToken) {
    return null;
  }

  if (tab === "compliance" && !showControlList && canManageTokenAdmin) {
    return "freeze";
  }

  if (tab === "compliance" && (!showControlList || !canManageTokenAdmin)) {
    return null;
  }

  return getDefaultActionForTab(tab);
}

function mergeWalletsPreferBalances(
  primaryWallets: PaymentsDashboardWallet[],
  secondaryWallets: PaymentsDashboardWallet[]
): PaymentsDashboardWallet[] {
  if (primaryWallets.length === 0) {
    return secondaryWallets;
  }

  if (secondaryWallets.length === 0) {
    return primaryWallets;
  }

  const secondaryById = new Map(secondaryWallets.map((wallet) => [wallet.id, wallet]));
  const merged = primaryWallets.map((wallet) => {
    const richerWallet = secondaryById.get(wallet.id);
    if (!richerWallet) {
      return wallet;
    }

    return Array.isArray(richerWallet.balances)
      ? { ...wallet, balances: richerWallet.balances }
      : wallet;
  });

  const primaryIds = new Set(primaryWallets.map((wallet) => wallet.id));
  for (const wallet of secondaryWallets) {
    if (!primaryIds.has(wallet.id)) {
      merged.push(wallet);
    }
  }

  return merged;
}

function LoadingSection({ message }: { message: string }) {
  return (
    <div className="flex min-h-[180px] items-center justify-center rounded-2xl border border-border-subtle bg-fill-subtle px-6 py-10">
      <div className="flex items-center gap-3 text-sm text-secondary">
        <Loader2Icon className="size-4 animate-spin" />
        <span>{message}</span>
      </div>
    </div>
  );
}

function canLoadAuthorityWallets(
  activeTab: TokenManagementTab,
  tokenStatus: TokenManagementWorkspaceProps["token"]["status"]
): boolean {
  return activeTab !== "overview" || tokenStatus === "pending";
}

// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: token management intentionally centralizes action orchestration and tab coordination in one workspace.
export function TokenManagementWorkspace({
  token,
  tokenError,
  authorityWallets: initialAuthorityWallets,
  authorityWalletsError: initialAuthorityWalletsError,
  transactions: initialTransactions,
  transactionsError: initialTransactionsError,
  transactionsTotal: initialTransactionsTotal,
  transactionsHasMore: initialTransactionsHasMore,
  allowlistEntries: initialAllowlistEntries,
  allowlistError: initialAllowlistError,
  allowlistTotal: initialAllowlistTotal,
  allowlistHasMore: initialAllowlistHasMore,
  frozenAccounts: initialFrozenAccounts,
  frozenAccountsError: initialFrozenAccountsError,
  frozenAccountsTotal: initialFrozenAccountsTotal,
  frozenAccountsHasMore: initialFrozenAccountsHasMore,
}: TokenManagementWorkspaceProps) {
  const t = useTranslations();
  const { dashboardAccess } = useDashboardWorkspace();
  const searchParams = useSearchParams();
  const { pushSearchParams, replaceSearchParams } = useDashboardUrlState();
  const {
    isPending,
    actionConfirmation,
    runAction: runActionBase,
    runActionImmediately: runActionImmediatelyBase,
    dismissActionConfirmation,
    confirmAction,
  } = useTokenActionRunner();
  const [activeAction, setActiveAction] = useState<AdminAction | null>(null);
  const [authorityModalRow, setAuthorityModalRow] = useState<PermissionRow | null>(null);
  const [authorityModalCurrentAuthority, setAuthorityModalCurrentAuthority] = useState<
    string | null
  >(null);
  const [authorityModalNewAuthority, setAuthorityModalNewAuthority] = useState("");
  const [authorityModalSignerWalletId, setAuthorityModalSignerWalletId] = useState("");
  const [fundManagementModalAction, setFundManagementModalAction] =
    useState<FundManagementModalAction | null>(null);
  const [deploySignerWalletId, setDeploySignerWalletId] = useState("");
  const [metadataForm, setMetadataForm] = useState(() => createInitialMetadataForm(token));
  const [mintForm, setMintForm] = useState(createInitialMintForm);
  const [burnForm, setBurnForm] = useState(createInitialBurnForm);
  const [seizeForm, setSeizeForm] = useState(createInitialSeizeForm);
  const [forceBurnForm, setForceBurnForm] = useState(createInitialForceBurnForm);
  const [authorityForm, setAuthorityForm] = useState(createInitialAuthorityForm);
  const [freezeForm, setFreezeForm] = useState(createInitialFreezeForm);
  const [allowlistForm, setAllowlistForm] = useState(createInitialAllowlistForm);
  const canManageTokenAdmin = dashboardAccess.capabilities.canManageTokenAdmin;
  const accessControlMode = getTokenAccessControlMode(token);
  const controlListCopy = getControlListCopy(accessControlMode, t);
  const managementTabs: Array<{ id: TokenManagementTab; label: string }> = [
    { id: "overview", label: t("DashboardIssuance.management.overview") },
    { id: "permissions", label: t("DashboardIssuance.management.permissions") },
    { id: "extensions", label: t("DashboardIssuance.management.extensions") },
    { id: "compliance", label: t("DashboardIssuance.management.compliance") },
    { id: "metadata", label: t("DashboardIssuance.management.metadata") },
    { id: "fund-management", label: t("DashboardIssuance.management.operations") },
  ];
  const liveFundManagementRows: Array<{
    id: FundManagementModalAction;
    title: string;
    helper: string;
    actionLabel: string;
  }> = [
    {
      id: "mint",
      title: t("DashboardIssuance.management.mintTokens"),
      helper: t("DashboardIssuance.management.mintHelper"),
      actionLabel: t("DashboardIssuance.management.mint"),
    },
    {
      id: "burn",
      title: t("DashboardIssuance.management.burnTokens"),
      helper: t("DashboardIssuance.management.burnHelper"),
      actionLabel: t("DashboardIssuance.management.burn"),
    },
  ];
  const showControlList = hasAccessControlList(accessControlMode);
  const visibleManagementTabs = managementTabs.filter(
    (tab) => tab.id !== "compliance" || showControlList || canManageTokenAdmin
  );
  const requestedTabParam = searchParams.get("tab");
  const requestedTab = isTokenManagementTab(requestedTabParam) ? requestedTabParam : null;
  const activeTab: TokenManagementTab =
    requestedTab && visibleManagementTabs.some((tab) => tab.id === requestedTab)
      ? requestedTab
      : "overview";
  const shouldLoadSupportingData = activeTab !== "overview";
  const shouldLoadAuthorityWallets = canLoadAuthorityWallets(activeTab, token.status);
  const hasInitialSupportingData =
    initialAuthorityWallets.length > 0 ||
    initialTransactions.length > 0 ||
    initialAllowlistEntries.length > 0 ||
    initialFrozenAccounts.length > 0 ||
    initialAuthorityWalletsError !== null ||
    initialTransactionsError !== null ||
    initialAllowlistError !== null ||
    initialFrozenAccountsError !== null;
  const initialSupportingData = useMemo<TokenManagementSupportingData>(
    () => ({
      authorityWallets: initialAuthorityWallets,
      authorityWalletsError: initialAuthorityWalletsError,
      transactions: initialTransactions,
      transactionsError: initialTransactionsError,
      transactionsTotal: initialTransactionsTotal,
      transactionsHasMore: initialTransactionsHasMore,
      allowlistEntries: initialAllowlistEntries,
      allowlistError: initialAllowlistError,
      allowlistTotal: initialAllowlistTotal,
      allowlistHasMore: initialAllowlistHasMore,
      frozenAccounts: initialFrozenAccounts,
      frozenAccountsError: initialFrozenAccountsError,
      frozenAccountsTotal: initialFrozenAccountsTotal,
      frozenAccountsHasMore: initialFrozenAccountsHasMore,
    }),
    [
      initialAllowlistEntries,
      initialAllowlistError,
      initialAllowlistHasMore,
      initialAllowlistTotal,
      initialAuthorityWallets,
      initialAuthorityWalletsError,
      initialFrozenAccounts,
      initialFrozenAccountsError,
      initialFrozenAccountsHasMore,
      initialFrozenAccountsTotal,
      initialTransactions,
      initialTransactionsError,
      initialTransactionsHasMore,
      initialTransactionsTotal,
    ]
  );
  const {
    data: authorityWalletsData,
    error: authorityWalletsRequestError,
    mutate: mutateAuthorityWallets,
  } = usePersistedDashboardSWR(
    shouldLoadAuthorityWallets ? ["token-management-authority-wallets", token.id] : null,
    ([, tokenId]: readonly [string, string]) => fetchTokenAuthorityWallets(tokenId, t),
    {
      fallbackData:
        initialAuthorityWallets.length > 0 || initialAuthorityWalletsError !== null
          ? ({
              authorityWallets: initialAuthorityWallets,
              authorityWalletsError: initialAuthorityWalletsError,
            } satisfies TokenAuthorityWalletsData)
          : undefined,
      refreshInterval: 60_000,
      revalidateOnFocus: true,
      revalidateIfStale: true,
    },
    {
      key: `token.${token.id}.authority-wallets`,
      ttlMs: TOKEN_AUTHORITY_WALLETS_CACHE_TTL_MS,
    }
  );
  const {
    data: supportingData,
    error: supportingDataRequestError,
    mutate: mutateSupportingData,
  } = usePersistedDashboardSWR(
    shouldLoadSupportingData ? ["token-management-supporting-data", token.id] : null,
    ([, tokenId]: readonly [string, string]) => fetchTokenManagementSupportingData(tokenId, t),
    {
      fallbackData: hasInitialSupportingData ? initialSupportingData : undefined,
      refreshInterval: 60_000,
      revalidateOnFocus: true,
      revalidateIfStale: true,
    },
    {
      key: `token.${token.id}.supporting-data`,
      ttlMs: TOKEN_SUPPORTING_DATA_CACHE_TTL_MS,
    }
  );
  const supportingDataError = supportingDataRequestError
    ? supportingDataRequestError instanceof Error
      ? supportingDataRequestError.message
      : t("DashboardIssuance.management.unableToLoadData")
    : null;
  const supportingDataLoading =
    shouldLoadSupportingData && supportingData === undefined && !supportingDataError;
  const resolvedSupportingData = supportingData ?? initialSupportingData;
  const authorityWalletsFetchError = authorityWalletsRequestError
    ? authorityWalletsRequestError instanceof Error
      ? authorityWalletsRequestError.message
      : t("DashboardIssuance.management.unableToLoadSignerWallets")
    : null;
  const authorityWalletsLoading =
    shouldLoadAuthorityWallets && authorityWalletsData === undefined && !authorityWalletsFetchError;
  const revalidateSupportingDataAfterSuccess = async () => {
    if (!shouldLoadSupportingData) {
      return;
    }

    await mutateSupportingData();
  };
  const revalidateAuthorityWalletsAfterSuccess = async () => {
    if (!shouldLoadAuthorityWallets) {
      return;
    }

    await mutateAuthorityWallets();
  };
  const runAction = (input: ActionExecutionInput, options: RunActionOptions = {}) =>
    runActionBase(input, {
      ...options,
      onSuccess: async (result) => {
        await options.onSuccess?.(result);
        await revalidateAuthorityWalletsAfterSuccess();
        await revalidateSupportingDataAfterSuccess();
      },
    });
  const runActionImmediately = (input: ActionExecutionInput, options: RunActionOptions = {}) =>
    runActionImmediatelyBase(input, {
      ...options,
      onSuccess: async (result) => {
        await options.onSuccess?.(result);
        await revalidateAuthorityWalletsAfterSuccess();
        await revalidateSupportingDataAfterSuccess();
      },
    });
  const authorityWallets = mergeWalletsPreferBalances(
    authorityWalletsData?.authorityWallets ?? [],
    resolvedSupportingData.authorityWallets
  );
  const authorityWalletsError =
    authorityWalletsFetchError ??
    authorityWalletsData?.authorityWalletsError ??
    supportingDataError ??
    resolvedSupportingData.authorityWalletsError;
  const transactions = resolvedSupportingData.transactions;
  const transactionsError = supportingDataError ?? resolvedSupportingData.transactionsError;
  const transactionsTotal = resolvedSupportingData.transactionsTotal;
  const transactionsHasMore = resolvedSupportingData.transactionsHasMore;
  const allowlistEntries = resolvedSupportingData.allowlistEntries;
  const allowlistError = supportingDataError ?? resolvedSupportingData.allowlistError;
  const allowlistTotal = resolvedSupportingData.allowlistTotal;
  const allowlistHasMore = resolvedSupportingData.allowlistHasMore;
  const frozenAccounts = resolvedSupportingData.frozenAccounts;
  const frozenAccountsError = supportingDataError ?? resolvedSupportingData.frozenAccountsError;
  const frozenAccountsTotal = resolvedSupportingData.frozenAccountsTotal;
  const frozenAccountsHasMore = resolvedSupportingData.frozenAccountsHasMore;

  const tokenBasePath = `/api/dashboard/issuance/tokens/${token.id}`;
  const explorerHref = getExplorerHref(token.mintAddress);
  const canDeployToken = token.status === "pending" && !token.mintAddress;
  const {
    mintDisabledReason,
    burnDisabledReason,
    seizeDisabledReason,
    forceBurnDisabledReason,
    pauseDisabledReason,
    freezeDisabledReason,
  } = getTokenActionDisabledReasons(token, t);
  const metadataAuthority = token.metadataAuthority ?? token.mintAuthority;
  const withWalletLoadError = <T extends { unavailableReason: string | null }>(selection: T): T => {
    if (authorityWalletsLoading && selection.unavailableReason) {
      return {
        ...selection,
        unavailableReason: t("DashboardIssuance.management.loadingSignerWallets"),
      };
    }

    if (authorityWalletsError && selection.unavailableReason) {
      return { ...selection, unavailableReason: authorityWalletsError };
    }

    return selection;
  };
  const deploySignerSelection = withWalletLoadError(
    getSignerSelectionForAction({
      action: "deploy",
      token,
      authorityWallets,
      metadataAuthority,
      t,
    })
  );
  const mintSignerSelection = withWalletLoadError(
    getSignerSelectionForAction({
      action: "mint",
      token,
      authorityWallets,
      metadataAuthority,
      t,
    })
  );
  const burnSignerSelection = withWalletLoadError(
    getSignerSelectionForAction({
      action: "burn",
      token,
      authorityWallets,
      metadataAuthority,
      t,
    })
  );
  const seizeSignerSelection = withWalletLoadError(
    getSignerSelectionForAction({
      action: "seize",
      token,
      authorityWallets,
      metadataAuthority,
      t,
    })
  );
  const forceBurnSignerSelection = withWalletLoadError(
    getSignerSelectionForAction({
      action: "force-burn",
      token,
      authorityWallets,
      metadataAuthority,
      t,
    })
  );
  const freezeSignerSelection = withWalletLoadError(
    getSignerSelectionForAction({
      action: "freeze",
      token,
      authorityWallets,
      metadataAuthority,
      t,
    })
  );
  const pauseSignerSelection = withWalletLoadError(
    getSignerSelectionForAction({
      action: "pause",
      token,
      authorityWallets,
      metadataAuthority,
      t,
    })
  );
  const permissionRows = getPermissionRows(token, metadataAuthority, t).map((row) => {
    const displayedAuthorityAddress = getDisplayedAuthorityAddress({
      token,
      role: row.authorityRole,
      metadataAuthority,
      authorityWallets,
    });
    const rowWithDisplayedValue = {
      ...row,
      value: displayedAuthorityAddress,
    };

    return {
      ...rowWithDisplayedValue,
      editDisabledReason: canManageTokenAdmin
        ? withWalletLoadError(
            getSignerSelectionForAction({
              action: "authority",
              token,
              authorityWallets,
              metadataAuthority,
              t,
              permissionRow: rowWithDisplayedValue,
            })
          ).unavailableReason
        : t("DashboardIssuance.management.onlyAdminsCanEditAuthorities"),
    };
  });
  const displayedMintAuthority = getDisplayedAuthorityAddress({
    token,
    role: "mint",
    metadataAuthority,
    authorityWallets,
  });
  const extensionRows = getExtensionRows(token, t);
  const complianceActions: Array<{ id: AdminAction; label: string }> = [
    ...(controlListCopy ? [{ id: "allowlist" as const, label: controlListCopy.label }] : []),
    ...(canManageTokenAdmin
      ? [
          { id: "seize" as const, label: t("DashboardIssuance.compliance.forceTransfer") },
          { id: "force-burn" as const, label: t("DashboardIssuance.compliance.forceBurn") },
          { id: "freeze" as const, label: t("DashboardIssuance.compliance.freeze") },
          { id: "pause" as const, label: t("DashboardIssuance.compliance.pause") },
        ]
      : []),
  ];
  const effectiveMintDisabledReason = mintDisabledReason ?? mintSignerSelection.unavailableReason;
  const effectiveBurnDisabledReason = burnDisabledReason ?? burnSignerSelection.unavailableReason;
  const effectiveSeizeDisabledReason =
    seizeDisabledReason ?? seizeSignerSelection.unavailableReason;
  const effectiveForceBurnDisabledReason =
    forceBurnDisabledReason ?? forceBurnSignerSelection.unavailableReason;
  const effectiveFreezeDisabledReason =
    freezeDisabledReason ?? freezeSignerSelection.unavailableReason;
  const effectivePauseDisabledReason =
    pauseDisabledReason ?? pauseSignerSelection.unavailableReason;
  const selectedBurnSignerWallet =
    findWalletByWalletId(
      burnSignerSelection.wallets,
      burnForm.signingWalletId || burnSignerSelection.defaultWalletId
    ) ??
    burnSignerSelection.wallets[0] ??
    null;
  const mintValidationReason = getMintValidationReason({
    token,
    destination: mintForm.destination,
    amount: mintForm.amount,
    allowlistEntries,
    t,
  });
  const mintValidationErrors = getMintValidationErrors({
    token,
    destination: mintForm.destination,
    amount: mintForm.amount,
    allowlistEntries,
    t,
  });
  const burnValidationReason = getBurnValidationReason({
    token,
    source: burnForm.source,
    amount: burnForm.amount,
    signerWallet: selectedBurnSignerWallet,
    walletOptions: authorityWallets,
    t,
  });
  const burnValidationErrors = getBurnValidationErrors({
    token,
    source: burnForm.source,
    amount: burnForm.amount,
    signerWallet: selectedBurnSignerWallet,
    walletOptions: authorityWallets,
    t,
  });
  const seizeValidationReason = getSeizeValidationReason({
    token,
    source: seizeForm.source,
    destination: seizeForm.destination,
    amount: seizeForm.amount,
    allowlistEntries,
    walletOptions: authorityWallets,
    t,
  });
  const seizeValidationErrors = getSeizeValidationErrors({
    token,
    source: seizeForm.source,
    destination: seizeForm.destination,
    amount: seizeForm.amount,
    allowlistEntries,
    walletOptions: authorityWallets,
    t,
  });
  const forceBurnValidationReason = getForceBurnValidationReason({
    token,
    source: forceBurnForm.source,
    amount: forceBurnForm.amount,
    walletOptions: authorityWallets,
    t,
  });
  const forceBurnValidationErrors = getForceBurnValidationErrors({
    token,
    source: forceBurnForm.source,
    amount: forceBurnForm.amount,
    walletOptions: authorityWallets,
    t,
  });
  const fundManagementDisabledReasons: Record<FundManagementModalAction, string | null> = {
    deploy: deploySignerSelection.unavailableReason,
    mint: effectiveMintDisabledReason ?? mintValidationReason,
    burn: effectiveBurnDisabledReason ?? burnValidationReason,
  };
  const complianceActionDisabledReasons: Partial<Record<AdminAction, string | null>> = {
    seize: effectiveSeizeDisabledReason ?? seizeValidationReason,
    "force-burn": effectiveForceBurnDisabledReason ?? forceBurnValidationReason,
    freeze: effectiveFreezeDisabledReason,
    pause: effectivePauseDisabledReason,
  };
  const fundManagementRows = canDeployToken
    ? [
        {
          id: "deploy" as const,
          title: t("DashboardIssuance.management.deployToken"),
          helper: t("DashboardIssuance.management.deployHelper"),
          actionLabel: t("DashboardIssuance.header.deploy"),
          disabled: Boolean(fundManagementDisabledReasons.deploy),
          disabledReason: fundManagementDisabledReasons.deploy,
        },
      ]
    : liveFundManagementRows.map((row) => ({
        ...row,
        disabled: Boolean(fundManagementDisabledReasons[row.id]),
        disabledReason: fundManagementDisabledReasons[row.id],
      }));

  // Shallow update: the tabs are fully client-rendered, so a router.push RSC
  // refetch on every tab switch would only add latency.
  const syncActiveTabInUrl = useCallback(
    (nextTab: TokenManagementTab, mode: "push" | "replace" = "push") => {
      const sync = mode === "replace" ? replaceSearchParams : pushSearchParams;
      sync({ tab: nextTab === "overview" ? null : nextTab });
    },
    [pushSearchParams, replaceSearchParams]
  );

  useEffect(() => {
    if (!requestedTabParam) {
      return;
    }

    if (requestedTabParam !== activeTab || activeTab === "overview") {
      syncActiveTabInUrl(activeTab, "replace");
    }
  }, [activeTab, requestedTabParam, syncActiveTabInUrl]);

  useEffect(() => {
    const nextDefaultAction = getDefaultActionForActiveTab({
      tab: activeTab,
      canDeployToken,
      showControlList,
      canManageTokenAdmin,
    });

    setActiveAction((currentAction) =>
      currentAction && getTabForAction(currentAction) === activeTab
        ? currentAction
        : nextDefaultAction
    );
  }, [activeTab, canDeployToken, showControlList, canManageTokenAdmin]);

  useEffect(() => {
    if (activeTab !== "fund-management" && fundManagementModalAction) {
      setFundManagementModalAction(null);
    }
  }, [activeTab, fundManagementModalAction]);

  const handleCopy = async (
    value: string | null,
    successMessage = t("DashboardIssuance.management.copied")
  ) => {
    if (!value) {
      return;
    }

    try {
      await navigator.clipboard.writeText(value);
      toast.success(successMessage);
    } catch {
      toast.error(t("DashboardIssuance.management.unableToCopy"));
    }
  };

  const handleUpdateMetadata = () => {
    const nextName = metadataForm.name.trim();
    if (!nextName) {
      toast.error(t("DashboardIssuance.management.tokenNameRequired"));
      return;
    }

    runAction({
      label: t("DashboardIssuance.management.updateToken"),
      method: "PATCH",
      path: tokenBasePath,
      body: {
        name: nextName,
        description: metadataForm.description.trim() ? metadataForm.description.trim() : null,
        uri: metadataForm.uri.trim() ? metadataForm.uri.trim() : null,
        imageUrl: metadataForm.imageUrl.trim() ? metadataForm.imageUrl.trim() : null,
      },
    });
  };

  const deployToken = (feePayment: DeployFeePayment) => {
    closeFundManagementModal();
    void runActionImmediately(
      {
        label: t("DashboardIssuance.management.deployToken"),
        method: "POST",
        path: `${tokenBasePath}/deploy`,
        body: {
          signingWalletId: deploySignerWalletId || undefined,
          feePayment,
        },
      },
      {
        submitToast: t("DashboardIssuance.management.submittingDeploy"),
        successToast: t("DashboardIssuance.management.deployFinalized"),
      }
    );
  };

  const handleRefreshSupply = () => {
    runAction({
      label: t("DashboardIssuance.management.refreshSupply"),
      method: "POST",
      path: `${tokenBasePath}/refresh-supply`,
      body: {},
    });
  };

  const handleMint = () => {
    if (effectiveMintDisabledReason) {
      toast.error(effectiveMintDisabledReason);
      return;
    }

    const destination = mintForm.destination.trim();
    const amount = mintForm.amount.trim();
    if (!destination || !amount) {
      toast.error(t("DashboardIssuance.management.mintDetailsRequired"));
      return;
    }
    if (mintValidationReason) {
      toast.error(mintValidationReason);
      return;
    }
    if (!isPositiveAmount(amount)) {
      toast.error(t("DashboardIssuance.management.amountPositive"));
      return;
    }

    runAction(
      {
        label: t("DashboardIssuance.management.mintTokens"),
        method: "POST",
        path: `${tokenBasePath}/mint`,
        body: {
          signingWalletId: mintForm.signingWalletId || undefined,
          mint: {
            destination,
            amount,
            memo: asOptionalString(mintForm.memo),
          },
        },
      },
      {
        requiresConfirmation: true,
        confirmationTitle: t("DashboardIssuance.management.mintConfirmationTitle"),
        confirmationDescription: t("DashboardIssuance.management.mintConfirmationDescription"),
        confirmButtonLabel: t("DashboardIssuance.management.mintNow"),
        submitToast: t("DashboardIssuance.management.submittingMint"),
        successToast: t("DashboardIssuance.management.mintFinalized"),
      }
    );
  };

  const handleBurn = () => {
    if (effectiveBurnDisabledReason) {
      toast.error(effectiveBurnDisabledReason);
      return;
    }

    const source = burnForm.source.trim();
    const amount = burnForm.amount.trim();
    if (!source || !amount) {
      toast.error(t("DashboardIssuance.management.burnDetailsRequired"));
      return;
    }
    if (burnValidationReason) {
      toast.error(burnValidationReason);
      return;
    }
    if (!isPositiveAmount(amount)) {
      toast.error(t("DashboardIssuance.management.amountPositive"));
      return;
    }

    runAction(
      {
        label: t("DashboardIssuance.management.burnTokens"),
        method: "POST",
        path: `${tokenBasePath}/burn`,
        body: {
          signingWalletId: burnForm.signingWalletId || undefined,
          burn: {
            source,
            amount,
            memo: asOptionalString(burnForm.memo),
          },
        },
      },
      {
        requiresConfirmation: true,
        confirmationTitle: t("DashboardIssuance.management.burnConfirmationTitle"),
        confirmationDescription: t("DashboardIssuance.management.burnConfirmationDescription"),
        confirmButtonLabel: t("DashboardIssuance.management.burnNow"),
        submitToast: t("DashboardIssuance.management.submittingBurn"),
        successToast: t("DashboardIssuance.management.burnFinalized"),
      }
    );
  };

  const handleSeize = () => {
    if (effectiveSeizeDisabledReason) {
      toast.error(effectiveSeizeDisabledReason);
      return;
    }

    const source = seizeForm.source.trim();
    const destination = seizeForm.destination.trim();
    const amount = seizeForm.amount.trim();
    if (!source || !destination || !amount) {
      toast.error(t("DashboardIssuance.management.seizeDetailsRequired"));
      return;
    }
    if (seizeValidationReason) {
      toast.error(seizeValidationReason);
      return;
    }
    if (!isPositiveAmount(amount)) {
      toast.error(t("DashboardIssuance.management.amountPositive"));
      return;
    }

    runAction(
      {
        label: t("DashboardIssuance.compliance.forceTransfer"),
        method: "POST",
        path: `${tokenBasePath}/seize`,
        body: {
          signingWalletId: seizeForm.signingWalletId || undefined,
          seize: {
            source,
            destination,
            amount,
            delegateAuthority: asOptionalString(seizeForm.delegateAuthority),
            memo: asOptionalString(seizeForm.memo),
          },
        },
      },
      {
        requiresConfirmation: true,
        confirmationTitle: t("DashboardIssuance.management.seizeConfirmationTitle"),
        confirmationDescription: t("DashboardIssuance.management.seizeConfirmationDescription"),
        confirmButtonLabel: t("DashboardIssuance.management.transferNow"),
        submitToast: t("DashboardIssuance.management.submittingForceTransfer"),
        successToast: t("DashboardIssuance.management.forceTransferFinalized"),
      }
    );
  };

  const handleForceBurn = () => {
    if (effectiveForceBurnDisabledReason) {
      toast.error(effectiveForceBurnDisabledReason);
      return;
    }

    const source = forceBurnForm.source.trim();
    const amount = forceBurnForm.amount.trim();
    if (!source || !amount) {
      toast.error(t("DashboardIssuance.management.forceBurnDetailsRequired"));
      return;
    }
    if (forceBurnValidationReason) {
      toast.error(forceBurnValidationReason);
      return;
    }
    if (!isPositiveAmount(amount)) {
      toast.error(t("DashboardIssuance.management.amountPositive"));
      return;
    }

    runAction(
      {
        label: t("DashboardIssuance.compliance.forceBurn"),
        method: "POST",
        path: `${tokenBasePath}/force-burn`,
        body: {
          signingWalletId: forceBurnForm.signingWalletId || undefined,
          forceBurn: {
            source,
            amount,
            delegateAuthority: asOptionalString(forceBurnForm.delegateAuthority),
            memo: asOptionalString(forceBurnForm.memo),
          },
        },
      },
      {
        requiresConfirmation: true,
        confirmationTitle: t("DashboardIssuance.management.forceBurnConfirmationTitle"),
        confirmationDescription: t("DashboardIssuance.management.forceBurnConfirmationDescription"),
        confirmButtonLabel: t("DashboardIssuance.management.forceBurnNow"),
        submitToast: t("DashboardIssuance.management.submittingForceBurn"),
        successToast: t("DashboardIssuance.management.forceBurnFinalized"),
      }
    );
  };

  const handleAuthorityUpdate = () => {
    runAction(
      {
        label: t("DashboardIssuance.management.updateAuthority"),
        method: "POST",
        path: `${tokenBasePath}/authority`,
        body: {
          authority: {
            role: authorityForm.role,
            currentAuthority: asOptionalString(authorityForm.currentAuthority),
            newAuthority: authorityForm.newAuthority.trim() || null,
          },
        },
      },
      {
        requiresConfirmation: true,
        confirmationTitle: t("DashboardIssuance.management.authorityConfirmationTitle"),
        confirmationDescription: t("DashboardIssuance.management.authorityConfirmationDescription"),
        confirmButtonLabel: t("DashboardIssuance.management.updateNow"),
        submitToast: t("DashboardIssuance.management.submittingAuthority"),
        successToast: t("DashboardIssuance.management.authorityFinalized"),
      }
    );
  };

  const handlePause = (pause: boolean) => {
    if (effectivePauseDisabledReason) {
      toast.error(effectivePauseDisabledReason);
      return;
    }

    runAction(
      {
        label: pause
          ? t("DashboardIssuance.management.pauseToken")
          : t("DashboardIssuance.management.unpauseToken"),
        method: "POST",
        path: `${tokenBasePath}/${pause ? "pause" : "unpause"}`,
        body: {},
      },
      {
        requiresConfirmation: true,
        confirmationTitle: pause
          ? t("DashboardIssuance.management.pauseConfirmationTitle")
          : t("DashboardIssuance.management.unpauseConfirmationTitle"),
        confirmationDescription: pause
          ? t("DashboardIssuance.management.pauseConfirmationDescription")
          : t("DashboardIssuance.management.unpauseConfirmationDescription"),
        confirmButtonLabel: pause
          ? t("DashboardIssuance.management.pauseNow")
          : t("DashboardIssuance.management.unpauseNow"),
        submitToast: pause
          ? t("DashboardIssuance.management.submittingPause")
          : t("DashboardIssuance.management.submittingUnpause"),
        successToast: pause
          ? t("DashboardIssuance.management.pauseFinalized")
          : t("DashboardIssuance.management.unpauseFinalized"),
      }
    );
  };

  const handleFreeze = (unfreeze: boolean) => {
    if (effectiveFreezeDisabledReason) {
      toast.error(effectiveFreezeDisabledReason);
      return;
    }

    const accountAddress = freezeForm.accountAddress.trim();
    if (!accountAddress) {
      toast.error(t("DashboardIssuance.management.accountAddressRequired"));
      return;
    }

    if (unfreeze) {
      runAction(
        {
          label: t("DashboardIssuance.management.unfreezeAccount"),
          method: "POST",
          path: `${tokenBasePath}/unfreeze`,
          body: {
            accountAddress,
          },
        },
        {
          requiresConfirmation: true,
          confirmationTitle: t("DashboardIssuance.management.unfreezeConfirmationTitle"),
          confirmationDescription: t(
            "DashboardIssuance.management.unfreezeConfirmationDescription"
          ),
          confirmButtonLabel: t("DashboardIssuance.management.unfreezeNow"),
          submitToast: t("DashboardIssuance.management.submittingUnfreeze"),
          successToast: t("DashboardIssuance.management.unfreezeFinalized"),
        }
      );
      return;
    }

    runAction(
      {
        label: t("DashboardIssuance.management.freezeAccount"),
        method: "POST",
        path: `${tokenBasePath}/freeze`,
        body: {
          accountAddress,
          reason: asOptionalString(freezeForm.reason),
        },
      },
      {
        requiresConfirmation: true,
        confirmationTitle: t("DashboardIssuance.management.freezeConfirmationTitle"),
        confirmationDescription: t("DashboardIssuance.management.freezeConfirmationDescription"),
        confirmButtonLabel: t("DashboardIssuance.management.freezeNow"),
        submitToast: t("DashboardIssuance.management.submittingFreeze"),
        successToast: t("DashboardIssuance.management.freezeFinalized"),
      }
    );
  };

  const handleAddAllowlist = () => {
    const address = allowlistForm.address.trim();
    if (!address) {
      toast.error(
        controlListCopy?.addressRequiredMessage ??
          t("DashboardIssuance.management.allowlistAddressRequired")
      );
      return;
    }

    runAction({
      label: controlListCopy?.addActionLabel ?? t("DashboardIssuance.management.addAllowlistEntry"),
      method: "POST",
      path: `${tokenBasePath}/allowlist`,
      body: {
        address,
        label: asOptionalString(allowlistForm.label),
      },
    });
  };

  const handleRemoveAllowlist = (entryId: string) => {
    runAction(
      {
        label:
          controlListCopy?.removeActionLabel ??
          t("DashboardIssuance.management.removeAllowlistEntry"),
        method: "DELETE",
        path: `${tokenBasePath}/allowlist/${entryId}`,
      },
      {
        onSuccess: async () => {
          await mutateSupportingData(
            (current) => {
              if (!current) {
                return current;
              }

              const allowlistEntries = current.allowlistEntries.filter(
                (entry) => entry.id !== entryId
              );
              const removedCount = current.allowlistEntries.length - allowlistEntries.length;
              const allowlistTotal =
                current.allowlistTotal === null
                  ? null
                  : Math.max(0, current.allowlistTotal - removedCount);

              return {
                ...current,
                allowlistEntries,
                allowlistTotal,
              };
            },
            { revalidate: false }
          );
        },
      }
    );
  };

  const handleAuthorityModalOpen = (row: PermissionRow) => {
    const currentAuthority = resolveAuthorityAddressForRole(
      token,
      row.authorityRole,
      metadataAuthority
    );
    const signerSelection = withWalletLoadError(
      getSignerSelectionForAction({
        action: "authority",
        token,
        authorityWallets,
        metadataAuthority,
        permissionRow: row,
        t,
      })
    );

    setAuthorityModalRow(row);
    setAuthorityModalCurrentAuthority(currentAuthority);
    setAuthorityModalNewAuthority(row.value ?? "");
    setAuthorityModalSignerWalletId(signerSelection.defaultWalletId);
  };

  const handleAuthorityModalClose = () => {
    if (isPending) {
      return;
    }

    setAuthorityModalRow(null);
    setAuthorityModalCurrentAuthority(null);
    setAuthorityModalNewAuthority("");
    setAuthorityModalSignerWalletId("");
  };

  const handleAuthorityModalConfirm = async () => {
    if (!authorityModalRow) {
      return;
    }

    const result = await runActionImmediately(
      {
        label: t("DashboardIssuance.management.updateAuthorityLabel", {
          authority: authorityModalRow.title,
        }),
        method: "POST",
        path: `${tokenBasePath}/authority`,
        body: {
          signingWalletId: authorityModalSignerWalletId || undefined,
          authority: {
            role: authorityModalRow.authorityRole,
            currentAuthority: authorityModalCurrentAuthority ?? undefined,
            newAuthority: asOptionalString(authorityModalNewAuthority) ?? null,
          },
        },
      },
      {
        submitToast: t("DashboardIssuance.management.updatingAuthority", {
          authority: authorityModalRow.title.toLowerCase(),
        }),
        successToast: t("DashboardIssuance.management.authorityUpdated", {
          authority: authorityModalRow.title,
        }),
      }
    );

    if (result.ok) {
      handleAuthorityModalClose();
    }
  };

  const openFundManagementModal = (action: FundManagementModalAction) => {
    if (fundManagementDisabledReasons[action]) {
      return;
    }

    switch (action) {
      case "deploy":
        setDeploySignerWalletId(deploySignerSelection.defaultWalletId);
        break;
      case "mint":
        setMintForm((previous) => ({
          ...previous,
          signingWalletId: mintSignerSelection.defaultWalletId,
        }));
        break;
      case "burn":
        setBurnForm((previous) => ({
          ...previous,
          signingWalletId: burnSignerSelection.defaultWalletId,
        }));
        break;
    }

    syncActiveTabInUrl("fund-management");
    setFundManagementModalAction(action);
  };

  const closeFundManagementModal = () => {
    if (isPending) {
      return;
    }

    setFundManagementModalAction(null);
  };

  const submitFundManagementAction = (action: FundManagementModalAction) => {
    closeFundManagementModal();

    switch (action) {
      case "mint":
        handleMint();
        return;
      case "burn":
        handleBurn();
        return;
    }
  };

  const handleTabChange = (tab: TokenManagementTab) => {
    syncActiveTabInUrl(tab);
  };

  const selectAction = (action: AdminAction) => {
    syncActiveTabInUrl(getTabForAction(action));
    setActiveAction(action);
  };

  const getActionSignerProps = (action: AdminAction | FundManagementModalAction | null) => {
    switch (action) {
      case "mint":
        return {
          signerWallets: mintSignerSelection.wallets,
          signerUnavailableReason: mintSignerSelection.unavailableReason,
          onSignerWalletIdChange: (value: string) =>
            setMintForm((previous) => ({ ...previous, signingWalletId: value })),
        };
      case "burn":
        return {
          signerWallets: burnSignerSelection.wallets,
          signerUnavailableReason: burnSignerSelection.unavailableReason,
          onSignerWalletIdChange: (value: string) =>
            setBurnForm((previous) => ({ ...previous, signingWalletId: value })),
        };
      case "seize":
        return {
          signerWallets: seizeSignerSelection.wallets,
          signerUnavailableReason: seizeSignerSelection.unavailableReason,
          onSignerWalletIdChange: (value: string) =>
            setSeizeForm((previous) => ({ ...previous, signingWalletId: value })),
        };
      case "force-burn":
        return {
          signerWallets: forceBurnSignerSelection.wallets,
          signerUnavailableReason: forceBurnSignerSelection.unavailableReason,
          onSignerWalletIdChange: (value: string) =>
            setForceBurnForm((previous) => ({ ...previous, signingWalletId: value })),
        };
      case "freeze":
        return {
          signerWallets: freezeSignerSelection.wallets,
          defaultSignerWalletId: freezeSignerSelection.defaultWalletId,
          signerUnavailableReason: freezeSignerSelection.unavailableReason,
          // Freeze authority is always single
          onSignerWalletIdChange: (_value: string) => {},
        };
      case "pause":
        return {
          signerWallets: pauseSignerSelection.wallets,
          defaultSignerWalletId: pauseSignerSelection.defaultWalletId,
          signerUnavailableReason: pauseSignerSelection.unavailableReason,
          // Pause authority is always single
          onSignerWalletIdChange: (_value: string) => {},
        };
      default:
        return {
          signerWallets: [],
          signerUnavailableReason: null,
          onSignerWalletIdChange: (_value: string) => {},
        };
    }
  };

  const visibleActionSignerProps = getActionSignerProps(activeAction);
  const fundManagementActionSignerProps = getActionSignerProps(fundManagementModalAction);
  const authorityModalSignerSelection = authorityModalRow
    ? withWalletLoadError(
        getSignerSelectionForAction({
          action: "authority",
          token,
          authorityWallets,
          metadataAuthority,
          permissionRow: authorityModalRow,
          t,
        })
      )
    : {
        wallets: [],
        defaultWalletId: "",
        unavailableReason: null,
      };

  const visibleActionForm =
    activeAction && getTabForAction(activeAction) === activeTab ? (
      <TokenActionForms
        activeAction={activeAction}
        isPending={isPending}
        tokenStatus={token.status}
        metadataForm={metadataForm}
        setMetadataForm={setMetadataForm}
        mintForm={mintForm}
        setMintForm={setMintForm}
        burnForm={burnForm}
        setBurnForm={setBurnForm}
        seizeForm={seizeForm}
        setSeizeForm={setSeizeForm}
        forceBurnForm={forceBurnForm}
        setForceBurnForm={setForceBurnForm}
        authorityForm={authorityForm}
        setAuthorityForm={setAuthorityForm}
        freezeForm={freezeForm}
        setFreezeForm={setFreezeForm}
        allowlistForm={allowlistForm}
        setAllowlistForm={setAllowlistForm}
        tokenId={token.id}
        allowlistEntries={allowlistEntries}
        allowlistError={allowlistError}
        controlListLabel={controlListCopy?.label ?? null}
        controlListDescription={controlListCopy?.description ?? null}
        controlListAddActionLabel={
          controlListCopy?.addActionLabel ?? t("DashboardIssuance.management.addAllowlistEntry")
        }
        controlListEmptyState={
          controlListCopy?.emptyState ?? t("DashboardIssuance.management.noAllowlistEntries")
        }
        freezeHint={controlListCopy?.freezeHint ?? null}
        signerWallets={visibleActionSignerProps.signerWallets}
        defaultSignerWalletId={visibleActionSignerProps.defaultSignerWalletId}
        walletOptions={authorityWallets}
        signerUnavailableReason={visibleActionSignerProps.signerUnavailableReason}
        mintValidationErrors={mintValidationErrors}
        mintValidationReason={mintValidationReason}
        burnValidationErrors={burnValidationErrors}
        burnValidationReason={burnValidationReason}
        seizeValidationErrors={seizeValidationErrors}
        seizeValidationReason={seizeValidationReason}
        forceBurnValidationErrors={forceBurnValidationErrors}
        forceBurnValidationReason={forceBurnValidationReason}
        submitAlignment="start"
        onSignerWalletIdChange={visibleActionSignerProps.onSignerWalletIdChange}
        onUpdateMetadata={handleUpdateMetadata}
        onMint={handleMint}
        onBurn={handleBurn}
        onSeize={handleSeize}
        onForceBurn={handleForceBurn}
        onAuthorityUpdate={handleAuthorityUpdate}
        onPause={handlePause}
        onFreeze={handleFreeze}
        onAddAllowlist={handleAddAllowlist}
        onRemoveAllowlist={handleRemoveAllowlist}
      />
    ) : null;

  return (
    <div className="space-y-8 pb-8">
      <TokenManagementHeader
        tokenId={token.id}
        tokenName={token.name}
        tokenSymbol={token.symbol}
        tokenStatus={token.status}
        tokenAddress={token.mintAddress}
        tokenImageUrl={token.imageUrl}
        explorerHref={explorerHref}
        canDeployToken={canDeployToken}
        isPending={isPending}
        deployDisabledReason={deploySignerSelection.unavailableReason}
        pauseDisabledReason={pauseDisabledReason}
        canManageTokenAdmin={canManageTokenAdmin}
        onCopyAddress={() => void handleCopy(token.mintAddress)}
        onCopyTokenId={() =>
          void handleCopy(token.id, t("DashboardIssuance.management.tokenIdCopied"))
        }
        onDeploy={() => {
          if (!canDeployToken) {
            return;
          }
          openFundManagementModal("deploy");
        }}
        onUnpause={() => handlePause(false)}
      />

      <div className="border-b border-border-default">
        <div className="flex flex-wrap gap-8">
          {visibleManagementTabs.map((tab) => (
            <button
              key={tab.id}
              type="button"
              onClick={() => handleTabChange(tab.id)}
              className={[
                "relative pb-4 text-[15px] leading-[24px] font-medium transition-colors sm:text-[16px]",
                activeTab === tab.id ? "text-primary" : "text-tertiary hover:text-primary",
              ].join(" ")}
            >
              {tab.label}
              {activeTab === tab.id ? (
                <span className="absolute right-0 bottom-[-1px] left-0 h-[2px] bg-primary" />
              ) : null}
            </button>
          ))}
        </div>
      </div>

      {tokenError ? (
        <div className="rounded-xl border border-error-border bg-error-bg px-4 py-3">
          <p className="text-sm font-medium text-error">
            {t("DashboardIssuance.workspace.tokenLoadWarning")}
          </p>
          <p className="mt-1 text-sm text-error">{tokenError}</p>
        </div>
      ) : null}

      {token.status === "paused" ? (
        <div className="flex flex-col gap-3 rounded-xl border border-warning-border bg-warning-bg px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
          <div>
            <p className="text-sm font-medium text-warning">
              {t("DashboardIssuance.workspace.tokenPaused")}
            </p>
            <p className="mt-1 text-sm text-warning">
              {t("DashboardIssuance.workspace.pausedHint")}
            </p>
          </div>
          {canManageTokenAdmin ? (
            <TokenDisabledActionTooltip reason={isPending ? null : effectivePauseDisabledReason}>
              <Button
                type="button"
                size="sm"
                onClick={() => handlePause(false)}
                disabled={isPending || Boolean(effectivePauseDisabledReason)}
              >
                {t("DashboardIssuance.workspace.unpauseToken")}
              </Button>
            </TokenDisabledActionTooltip>
          ) : null}
        </div>
      ) : null}

      {activeTab === "overview" ? (
        <div className="space-y-4">
          <TokenOverviewSection
            token={token}
            showTitle={false}
            mintAuthorityValue={displayedMintAuthority}
            onRefreshSupply={token.status !== "pending" ? handleRefreshSupply : undefined}
            refreshDisabled={isPending}
          />
        </div>
      ) : null}

      {activeTab === "permissions" ? (
        authorityWalletsLoading ? (
          <LoadingSection
            message={t("DashboardIssuance.management.loadingAuthorityWalletAccess")}
          />
        ) : (
          <div className="space-y-4">
            <TokenSettingsSection
              mode="permissions"
              permissionRows={permissionRows}
              extensionRows={extensionRows}
              authorityWallets={authorityWallets}
              showTitle={false}
              canEditAuthorities={!canDeployToken && canManageTokenAdmin}
              onCopy={handleCopy}
              onEditAuthority={handleAuthorityModalOpen}
            />
          </div>
        )
      ) : null}

      {activeTab === "extensions" ? (
        <div className="space-y-4">
          <TokenSettingsSection
            mode="extensions"
            permissionRows={permissionRows}
            extensionRows={extensionRows}
            authorityWallets={authorityWallets}
            showTitle={false}
            canEditAuthorities={!canDeployToken && canManageTokenAdmin}
            onCopy={handleCopy}
            onEditAuthority={handleAuthorityModalOpen}
          />
        </div>
      ) : null}

      {activeTab === "compliance" ? (
        supportingDataLoading ? (
          <LoadingSection message={t("DashboardIssuance.management.loadingComplianceControls")} />
        ) : (
          <div className="space-y-4">
            <ActionSelector
              actions={complianceActions}
              activeAction={activeAction}
              disabledReasons={complianceActionDisabledReasons}
              onSelectAction={selectAction}
            />
            <div className="grid gap-4 xl:grid-cols-[minmax(0,1fr)_320px]">
              <div>{visibleActionForm}</div>
              <TokenControlListsSection
                showControlList={showControlList}
                controlListLabel={controlListCopy?.label ?? null}
                allowlistEntriesCount={allowlistEntries.length}
                allowlistError={allowlistError}
                allowlistTotal={allowlistTotal}
                allowlistHasMore={allowlistHasMore}
                frozenAccountsCount={frozenAccounts.length}
                frozenAccountsError={frozenAccountsError}
                frozenAccountsTotal={frozenAccountsTotal}
                frozenAccountsHasMore={frozenAccountsHasMore}
              />
            </div>
          </div>
        )
      ) : null}

      {activeTab === "metadata" ? (
        <div className="space-y-4">
          {visibleActionForm}
          <TokenOverviewSection
            token={token}
            showTitle={false}
            mintAuthorityValue={displayedMintAuthority}
          />
        </div>
      ) : null}

      {activeTab === "fund-management" ? (
        <div className="space-y-4">
          <TokenFundManagementSection
            rows={fundManagementRows}
            onOpenAction={openFundManagementModal}
          />
          <TokenTransactionsSection
            transactions={transactions}
            transactionsError={transactionsError}
            transactionsTotal={transactionsTotal}
            transactionsHasMore={transactionsHasMore}
            isLoading={supportingDataLoading}
          />
        </div>
      ) : null}

      <TokenAuthorityModal
        row={authorityModalRow}
        currentAuthorityValue={authorityModalCurrentAuthority}
        newAuthority={authorityModalNewAuthority}
        authorityWallets={authorityWallets}
        authorityWalletsError={authorityWalletsError}
        signerUnavailableReason={authorityModalSignerSelection.unavailableReason}
        isPending={isPending}
        onNewAuthorityChange={setAuthorityModalNewAuthority}
        onCancel={handleAuthorityModalClose}
        onConfirm={handleAuthorityModalConfirm}
      />

      <TokenManagementModalShell
        isOpen={Boolean(fundManagementModalAction)}
        isPending={isPending}
        onClose={closeFundManagementModal}
      >
        {fundManagementModalAction === "deploy" ? (
          <div className="rounded-2xl border border-border-default bg-surface-raised p-5 shadow-[0_20px_40px_rgba(0,0,0,0.16)]">
            <p className="pr-12 text-[20px] leading-[1.2] font-medium text-primary">
              {t("DashboardIssuance.management.deployToken")}
            </p>
            <p className="mt-2 text-[14px] leading-[1.45] text-secondary">
              {t("DashboardIssuance.workspace.deployHint")}
            </p>
            <div className="mt-5 space-y-5">
              <TokenSignerSelect
                signerWallets={deploySignerSelection.wallets}
                signerWalletId={deploySignerWalletId}
                signerUnavailableReason={deploySignerSelection.unavailableReason}
                onSignerWalletIdChange={setDeploySignerWalletId}
                helperText={t("DashboardIssuance.management.deploySignerHint")}
              />
              <div className="flex items-center justify-between gap-2">
                <button
                  type="button"
                  onClick={closeFundManagementModal}
                  disabled={isPending}
                  className="inline-flex h-10 items-center rounded-[12px] border border-border-default bg-surface-raised px-4 text-sm font-medium text-primary transition-colors hover:bg-fill-subtle disabled:pointer-events-none disabled:opacity-50"
                >
                  {t("DashboardIssuance.workspace.cancel")}
                </button>
                <div className="flex items-center gap-2">
                  <button
                    type="button"
                    onClick={() => deployToken("wallet")}
                    disabled={isPending || Boolean(deploySignerSelection.unavailableReason)}
                    className="inline-flex h-10 items-center gap-2 rounded-[12px] border border-border-default bg-surface-raised px-4 text-sm font-medium text-primary transition-colors hover:bg-fill-subtle disabled:pointer-events-none disabled:opacity-50"
                  >
                    <WalletIcon className="size-4" />
                    {t("DashboardIssuance.management.deployWithWallet")}
                  </button>
                  <TokenDisabledActionTooltip
                    reason={t("DashboardIssuance.management.koraUnavailable")}
                  >
                    <button
                      type="button"
                      disabled
                      className="inline-flex h-10 items-center gap-2 rounded-[12px] bg-primary px-4 text-sm font-medium text-on-primary transition hover:opacity-90 disabled:pointer-events-none disabled:opacity-50"
                    >
                      <SparklesIcon className="size-4" />
                      {t("DashboardIssuance.management.deployWithKora")}
                    </button>
                  </TokenDisabledActionTooltip>
                </div>
              </div>
            </div>
          </div>
        ) : fundManagementModalAction ? (
          <TokenActionForms
            activeAction={fundManagementModalAction}
            isPending={isPending}
            tokenStatus={token.status}
            metadataForm={metadataForm}
            setMetadataForm={setMetadataForm}
            mintForm={mintForm}
            setMintForm={setMintForm}
            burnForm={burnForm}
            setBurnForm={setBurnForm}
            seizeForm={seizeForm}
            setSeizeForm={setSeizeForm}
            forceBurnForm={forceBurnForm}
            setForceBurnForm={setForceBurnForm}
            authorityForm={authorityForm}
            setAuthorityForm={setAuthorityForm}
            freezeForm={freezeForm}
            setFreezeForm={setFreezeForm}
            allowlistForm={allowlistForm}
            setAllowlistForm={setAllowlistForm}
            tokenId={token.id}
            allowlistEntries={allowlistEntries}
            allowlistError={allowlistError}
            controlListLabel={controlListCopy?.label ?? null}
            controlListDescription={controlListCopy?.description ?? null}
            controlListAddActionLabel={
              controlListCopy?.addActionLabel ?? t("DashboardIssuance.management.addAllowlistEntry")
            }
            controlListEmptyState={
              controlListCopy?.emptyState ?? t("DashboardIssuance.management.noAllowlistEntries")
            }
            freezeHint={controlListCopy?.freezeHint ?? null}
            signerWallets={fundManagementActionSignerProps.signerWallets}
            defaultSignerWalletId={fundManagementActionSignerProps.defaultSignerWalletId}
            walletOptions={authorityWallets}
            signerUnavailableReason={fundManagementActionSignerProps.signerUnavailableReason}
            mintValidationErrors={mintValidationErrors}
            mintValidationReason={mintValidationReason}
            burnValidationErrors={burnValidationErrors}
            burnValidationReason={burnValidationReason}
            seizeValidationErrors={seizeValidationErrors}
            seizeValidationReason={seizeValidationReason}
            forceBurnValidationErrors={forceBurnValidationErrors}
            forceBurnValidationReason={forceBurnValidationReason}
            submitAlignment="end"
            onSignerWalletIdChange={fundManagementActionSignerProps.onSignerWalletIdChange}
            onUpdateMetadata={handleUpdateMetadata}
            onMint={() => submitFundManagementAction("mint")}
            onBurn={() => submitFundManagementAction("burn")}
            onSeize={handleSeize}
            onForceBurn={handleForceBurn}
            onAuthorityUpdate={handleAuthorityUpdate}
            onPause={handlePause}
            onFreeze={handleFreeze}
            onAddAllowlist={handleAddAllowlist}
            onRemoveAllowlist={handleRemoveAllowlist}
          />
        ) : null}
      </TokenManagementModalShell>

      <TokenActionConfirmationDialog
        actionConfirmation={actionConfirmation}
        isPending={isPending}
        onCancel={dismissActionConfirmation}
        onConfirm={confirmAction}
      />

      {isPending ? (
        <div className="fixed right-4 bottom-4 z-30 inline-flex items-center gap-2 rounded-lg border border-border-default bg-surface-raised px-3 py-2 text-sm shadow-lg">
          <Loader2Icon className="h-4 w-4 animate-spin" />
          {t("DashboardIssuance.workspace.runningAction")}
        </div>
      ) : null}
    </div>
  );
}

function ActionSelector({
  actions,
  activeAction,
  disabledReasons,
  onSelectAction,
}: {
  actions: Array<{ id: AdminAction; label: string }>;
  activeAction: AdminAction | null;
  disabledReasons?: Partial<Record<AdminAction, string | null>>;
  onSelectAction: (action: AdminAction) => void;
}) {
  return (
    <div className="flex flex-wrap gap-2">
      {actions.map((action) => (
        <TokenDisabledActionTooltip key={action.id} reason={disabledReasons?.[action.id]}>
          <button
            type="button"
            onClick={() => onSelectAction(action.id)}
            disabled={Boolean(disabledReasons?.[action.id])}
            className={[
              "inline-flex h-10 items-center rounded-[12px] px-4 text-sm font-medium transition-colors",
              activeAction === action.id
                ? "bg-primary text-on-primary"
                : "bg-fill text-primary hover:bg-fill-strong disabled:pointer-events-none disabled:opacity-50",
            ].join(" ")}
          >
            {action.label}
          </button>
        </TokenDisabledActionTooltip>
      ))}
    </div>
  );
}
