import { useEffect, useMemo, useState } from "react";
import type { ApiSettings, AuthInfo, CampaignListItem } from "../../../types";
import {
  ArrowRightLeft,
  Check,
  KeyRound,
  Trash2,
  XCircle
} from "lucide-react";
import {
  fetchResourceAccessExplanation,
  getCampaignShares,
  campaignShareTargetProvider,
  revokeCampaignShare,
  upsertCampaignShare,
  type CampaignShare,
  type ResourceAccessExplanationResponse } from
"../../../api/campaigns";
import {
  Button,
  decideOwnershipTransfer,
  listOwnershipTransfers,
  ReferenceSelect,
  ResourceAccessExplanation,
  requestResourceOwnership,
  startOwnershipTransfer,
  type OwnershipTransfer,
  type ReferenceOption,
  type ReferenceOptionProvider
} from "@govoplan/core-webui";
import { Card } from "@govoplan/core-webui";
import { ConfirmDialog } from "@govoplan/core-webui";
import { DataGrid, type DataGridColumn } from "@govoplan/core-webui";
import { Dialog } from "@govoplan/core-webui";
import { FormField } from "@govoplan/core-webui";
import { StatusBadge, TableActionGroup, hasScope, i18nMessage, useUnsavedDraftGuard } from "@govoplan/core-webui";
type TargetType = "user" | "group";

export default function CampaignAccessCard({
  settings,
  auth,
  campaign,
  onChanged,
  onError





}: {settings: ApiSettings;auth: AuthInfo;campaign: CampaignListItem;onChanged: () => Promise<void>;onError: (message: string) => void;}) {
  const [available, setAvailable] = useState<boolean | null>(null);
  const [targets, setTargets] = useState<{
    users: readonly ReferenceOption[];
    groups: readonly ReferenceOption[];
  }>({ users: [], groups: [] });
  const [shares, setShares] = useState<CampaignShare[]>([]);
  const [ownerOpen, setOwnerOpen] = useState(false);
  const [requestOpen, setRequestOpen] = useState(false);
  const [shareOpen, setShareOpen] = useState(false);
  const [revokeTarget, setRevokeTarget] = useState<CampaignShare | null>(null);
  const [ownerType, setOwnerType] = useState<TargetType>(campaign.owner_group_id ? "group" : "user");
  const [ownerId, setOwnerId] = useState(campaign.owner_group_id || campaign.owner_user_id || "");
  const [ownerReason, setOwnerReason] = useState("");
  const [ownerExpiryDays, setOwnerExpiryDays] = useState(7);
  const [ownerRequestKey, setOwnerRequestKey] = useState("");
  const [requestTargetType, setRequestTargetType] = useState<TargetType>("user");
  const [requestGroupId, setRequestGroupId] = useState("");
  const [requestReason, setRequestReason] = useState("");
  const [requestKey, setRequestKey] = useState("");
  const [shareType, setShareType] = useState<TargetType>("user");
  const [shareTargetId, setShareTargetId] = useState("");
  const [sharePermission, setSharePermission] = useState<"read" | "write">("read");
  const [accessExplanationOpen, setAccessExplanationOpen] = useState(false);
  const [accessExplanation, setAccessExplanation] = useState<ResourceAccessExplanationResponse | null>(null);
  const [accessExplanationLoading, setAccessExplanationLoading] = useState(false);
  const [ownershipTransfers, setOwnershipTransfers] = useState<OwnershipTransfer[]>([]);
  const [busy, setBusy] = useState(false);
  const currentOwnerType: TargetType = campaign.owner_group_id ? "group" : "user";
  const currentOwnerId = campaign.owner_group_id || campaign.owner_user_id || "";
  const actorId = auth.principal?.membership_id || auth.user.id;
  const actorGroupIds = new Set(
    auth.principal?.group_ids ?? auth.groups.map((group) => group.id)
  );
  const actorIsCurrentOwner = (
    currentOwnerType === "user"
      ? currentOwnerId === actorId
      : actorGroupIds.has(currentOwnerId)
  );
  const canProposeOwnership = actorIsCurrentOwner && hasScope(
    auth,
    "campaigns:campaign:share"
  );
  const canRequestOwnership = !actorIsCurrentOwner && hasScope(
    auth,
    "campaigns:campaign:read"
  );
  const ownerDirty = ownerOpen && (
    ownerType !== currentOwnerType
    || ownerId !== currentOwnerId
    || Boolean(ownerReason)
    || ownerExpiryDays !== 7
  );
  const requestDirty = requestOpen && (
    requestTargetType !== "user"
    || Boolean(requestGroupId)
    || Boolean(requestReason)
  );
  const shareDirty = shareOpen && (shareType !== "user" || Boolean(shareTargetId) || sharePermission !== "read");
  const canExplainResourceAccess =
  hasScope(auth, "admin:users:read") ||
  hasScope(auth, "admin:roles:read") ||
  hasScope(auth, "access:membership:read") ||
  hasScope(auth, "access:role:read");
  const userTargetProvider = useMemo(
    () => campaignShareTargetProvider(settings, campaign.id, "user"),
    [campaign.id, settings.accessToken, settings.apiBaseUrl, settings.apiKey]
  );
  const groupTargetProvider = useMemo(
    () => campaignShareTargetProvider(settings, campaign.id, "group"),
    [campaign.id, settings.accessToken, settings.apiBaseUrl, settings.apiKey]
  );

  useUnsavedDraftGuard({
    dirty: ownerDirty || requestDirty || shareDirty,
    onSave: saveActiveDialog,
    onDiscard: () => {
      closeOwnerDialog();
      closeRequestDialog();
      closeShareDialog();
    }
  });

  async function load() {
    let nextShares: CampaignShare[] = [];
    let nextTransfers: OwnershipTransfer[] = [];
    try {
      nextTransfers = await listOwnershipTransfers(settings, {
        resourceType: "campaign",
        resourceId: campaign.id,
        limit: 100
      });
      setOwnershipTransfers(nextTransfers);
    } catch (err) {
      onError(err instanceof Error ? err.message : String(err));
    }
    try {
      nextShares = (await getCampaignShares(settings, campaign.id))
        .filter((item) => !item.revoked_at);
      setShares(nextShares);
      setAvailable(true);
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      if (message.startsWith("403 ")) {
        setAvailable(false);
      } else {
        onError(message);
      }
    }
    const userIds = uniqueTargetIds(
      nextShares,
      nextTransfers,
      "user",
      campaign.owner_user_id
    );
    const groupIds = uniqueTargetIds(
      nextShares,
      nextTransfers,
      "group",
      campaign.owner_group_id
    );
    const controller = new AbortController();
    try {
      const [users, groups] = await Promise.all([
        resolveReferenceOptions(userTargetProvider, userIds, controller.signal),
        resolveReferenceOptions(groupTargetProvider, groupIds, controller.signal)
      ]);
      setTargets({ users, groups });
    } catch (err) {
      onError(err instanceof Error ? err.message : String(err));
    }
  }

  useEffect(() => {
    setOwnerType(campaign.owner_group_id ? "group" : "user");
    setOwnerId(campaign.owner_group_id || campaign.owner_user_id || "");
    void load();
  }, [
    campaign.id,
    campaign.owner_group_id,
    campaign.owner_user_id,
    groupTargetProvider,
    settings.accessToken,
    settings.apiBaseUrl,
    settings.apiKey,
    userTargetProvider
  ]);

  const ownerTargetProvider = ownerType === "user" ? userTargetProvider : groupTargetProvider;
  const shareTargetProvider = shareType === "user" ? userTargetProvider : groupTargetProvider;
  const targetMap = useMemo(() => new Map([
  ...targets.users.map((item) => [`user:${item.value}`, item] as const),
  ...targets.groups.map((item) => [`group:${item.value}`, item] as const)]
  ), [targets]);

  const ownerLabel = campaign.owner_group_id ?
  targetMap.get(`group:${campaign.owner_group_id}`)?.label || "i18n:govoplan-campaign.group_owner.55630670" :
  targetMap.get(`user:${campaign.owner_user_id || ""}`)?.label || "i18n:govoplan-campaign.user_owner.86e3faab";

  function closeOwnerDialog() {
    setOwnerOpen(false);
    setOwnerType(currentOwnerType);
    setOwnerId(currentOwnerId);
    setOwnerReason("");
    setOwnerExpiryDays(7);
    setOwnerRequestKey("");
  }

  function openOwnerDialog() {
    setOwnerType(currentOwnerType);
    setOwnerId("");
    setOwnerReason("");
    setOwnerExpiryDays(7);
    setOwnerRequestKey(crypto.randomUUID());
    setOwnerOpen(true);
  }

  function closeRequestDialog() {
    setRequestOpen(false);
    setRequestTargetType("user");
    setRequestGroupId("");
    setRequestReason("");
    setRequestKey("");
  }

  function openRequestDialog() {
    setRequestTargetType("user");
    setRequestGroupId("");
    setRequestReason("");
    setRequestKey(crypto.randomUUID());
    setRequestOpen(true);
  }

  function closeShareDialog() {
    setShareOpen(false);
    setShareType("user");
    setShareTargetId("");
    setSharePermission("read");
  }

  async function saveActiveDialog(): Promise<boolean> {
    if (ownerDirty) return saveOwner();
    if (requestDirty) return requestOwnership();
    if (shareDirty) return saveShare();
    return true;
  }

  async function saveOwner(): Promise<boolean> {
    if (!ownerId || ownerId === currentOwnerId && ownerType === currentOwnerType) {
      return false;
    }
    setBusy(true);
    try {
      await startOwnershipTransfer(settings, {
        resource: {
          module_id: "campaigns",
          resource_type: "campaign",
          resource_id: campaign.id
        },
        target_owner: { type: ownerType, id: ownerId },
        idempotency_key: ownerRequestKey || crypto.randomUUID(),
        reason: ownerReason.trim() || null,
        expiry_days: ownerExpiryDays
      });
      closeOwnerDialog();
      await load();
      return true;
    } catch (err) {onError(err instanceof Error ? err.message : String(err));return false;} finally
    {setBusy(false);}
  }

  async function requestOwnership(): Promise<boolean> {
    const targetId = requestTargetType === "user" ? actorId : requestGroupId;
    if (!targetId) return false;
    setBusy(true);
    try {
      await requestResourceOwnership(settings, {
        resource: {
          module_id: "campaigns",
          resource_type: "campaign",
          resource_id: campaign.id
        },
        target_owner: { type: requestTargetType, id: targetId },
        idempotency_key: requestKey || crypto.randomUUID(),
        reason: requestReason.trim() || null,
        expiry_days: 7
      });
      closeRequestDialog();
      await load();
      return true;
    } catch (err) {
      onError(err instanceof Error ? err.message : String(err));
      return false;
    } finally {
      setBusy(false);
    }
  }

  async function performOwnershipAction(
    transfer: OwnershipTransfer,
    action: "owner-approval" | "acceptance" | "decline" | "cancel"
  ) {
    setBusy(true);
    try {
      await decideOwnershipTransfer(settings, transfer.id, action);
      await onChanged();
      await load();
    } catch (err) {
      onError(err instanceof Error ? err.message : String(err));
    } finally {
      setBusy(false);
    }
  }

  async function saveShare(): Promise<boolean> {
    if (!shareTargetId) return false;
    setBusy(true);
    try {
      await upsertCampaignShare(settings, campaign.id, { target_type: shareType, target_id: shareTargetId, permission: sharePermission });
      setShareOpen(false);
      setShareTargetId("");
      await load();
      return true;
    } catch (err) {onError(err instanceof Error ? err.message : String(err));return false;} finally
    {setBusy(false);}
  }

  async function revoke() {
    if (!revokeTarget) return;
    setBusy(true);
    try {
      await revokeCampaignShare(settings, campaign.id, revokeTarget.id);
      setRevokeTarget(null);
      await load();
    } catch (err) {onError(err instanceof Error ? err.message : String(err));} finally
    {setBusy(false);}
  }

  async function openAccessExplanation() {
    if (!auth.user?.id) return;
    setAccessExplanationOpen(true);
    setAccessExplanation(null);
    setAccessExplanationLoading(true);
    try {
      setAccessExplanation(await fetchResourceAccessExplanation(settings, {
        userId: auth.user.id,
        resourceType: "campaign",
        resourceId: campaign.id,
        action: "campaigns:campaign:read",
        tenantId: (auth.active_tenant ?? auth.tenant)?.id
      }));
    } catch (err) {
      onError(err instanceof Error ? err.message : String(err));
      setAccessExplanationOpen(false);
    } finally {
      setAccessExplanationLoading(false);
    }
  }

  const columns = useMemo<DataGridColumn<CampaignShare>[]>(() => [
  {
    id: "target",
    header: "i18n:govoplan-campaign.shared_with.6203f449",
    width: "minmax(220px, 1fr)",
    minWidth: 190,
    maxWidth: 560,
    resizable: true,
    sticky: "start",
    sortable: true,
    filterable: true,
    value: (row) => targetMap.get(`${row.target_type}:${row.target_id}`)?.label || row.target_id,
    render: (row) => {
      const target = targetMap.get(`${row.target_type}:${row.target_id}`);
      return <div><strong>{target?.label || row.target_id}</strong><div className="muted small-note">{row.target_type}{target?.description ? i18nMessage("i18n:govoplan-campaign.value.48afe802", { value0: target.description }) : ""}</div></div>;
    }
  },
  { id: "permission", header: "i18n:govoplan-campaign.access.2f81a22d", width: 120, resizable: false, sortable: true, filterable: true, value: (row) => row.permission, render: (row) => <StatusBadge status={row.permission === "write" ? "active" : "built"} label={row.permission === "write" ? "i18n:govoplan-campaign.can_edit.cb0ab3da" : "i18n:govoplan-campaign.can_view.1b3e4006"} /> },
  { id: "actions", header: "i18n:govoplan-campaign.actions.c3cd636a", width: 72, resizable: false, sticky: "end", align: "right", render: (row) => <TableActionGroup actions={[{ id: "remove", label: "i18n:govoplan-campaign.remove.e963907d", icon: <Trash2 aria-hidden="true" />, variant: "danger", onClick: () => setRevokeTarget(row) }]} /> }],
  [targetMap]);

  const canAcceptForGroup = hasScope(
    auth,
    "campaigns:ownership:accept_group"
  );

  return (
    <>
      <Card title="i18n:govoplan-campaign.ownership_and_sharing.867283c0" actions={<div className="button-row compact-actions">{canProposeOwnership ? <Button onClick={openOwnerDialog}><ArrowRightLeft size={16} aria-hidden="true" /> Transfer ownership</Button> : null}{canRequestOwnership ? <Button onClick={openRequestDialog}><ArrowRightLeft size={16} aria-hidden="true" /> Request ownership</Button> : null}<Button onClick={() => setShareOpen(true)} disabled={available !== true}>i18n:govoplan-campaign.share.09ca55ca</Button><Button onClick={() => void openAccessExplanation()} disabled={!canExplainResourceAccess}><KeyRound size={16} aria-hidden="true" /> i18n:govoplan-campaign.explain_access.4d5fac37</Button></div>}>
        <p><strong>i18n:govoplan-campaign.owner.719379ae</strong> {ownerLabel}</p>
        <p className="muted small-note">Ownership changes require acceptance by the new owner. They never transfer private encryption keys. A completed transfer clears owner-scoped mail profile selection and requires revalidation.</p>
        {ownershipTransfers.length > 0 ? (
          <section className="campaign-ownership-transfers">
            <h3>Ownership requests and history</h3>
            <div className="campaign-ownership-transfer-list">
              {ownershipTransfers.map((transfer) => {
                const actions = ownershipTransferActions(transfer, {
                  actorId,
                  actorGroupIds,
                  canShare: hasScope(auth, "campaigns:campaign:share"),
                  canAcceptForGroup
                });
                return (
                  <div className="campaign-ownership-transfer" key={transfer.id}>
                    <div className="campaign-ownership-transfer-main">
                      <span>
                        <strong>{ownershipSubjectLabel(transfer.target_owner, targetMap)}</strong>
                        <small>{ownershipPendingParty(transfer)}</small>
                      </span>
                      <StatusBadge status={transfer.status} label={transfer.status.replace(/_/g, " ")} />
                    </div>
                    <div className="campaign-ownership-transfer-meta">
                      <span>{transfer.kind.replace(/_/g, " ")}</span>
                      <span>Expires {formatOwnershipDate(transfer.expires_at)}</span>
                      {transfer.reason ? <span>{transfer.reason}</span> : null}
                    </div>
                    {actions.length > 0 ? (
                      <div className="button-row compact-actions">
                        {actions.map((action) => (
                          <Button
                            key={action.id}
                            variant={action.variant}
                            disabled={busy}
                            onClick={() => void performOwnershipAction(transfer, action.id)}
                          >
                            {action.id === "acceptance" || action.id === "owner-approval" ? <Check size={15} aria-hidden="true" /> : <XCircle size={15} aria-hidden="true" />}
                            {action.label}
                          </Button>
                        ))}
                      </div>
                    ) : null}
                  </div>
                );
              })}
            </div>
          </section>
        ) : null}
        {available === true ? (
          <DataGrid id={`campaign-${campaign.id}-shares`} rows={shares} columns={columns} getRowKey={(row) => row.id} emptyText="i18n:govoplan-campaign.this_campaign_has_no_explicit_shares.978012d1" />
        ) : (
          <p className="muted small-note">
            {available === null
              ? "i18n:govoplan-campaign.loading_campaign_access.056299e3"
              : "Explicit shares are visible only to authorized campaign access managers."}
          </p>
        )}
      </Card>

      <Dialog open={ownerOpen} className="campaign-access-dialog" title="Transfer campaign ownership" onClose={() => !busy && closeOwnerDialog()} footer={<><Button onClick={closeOwnerDialog} disabled={busy}>i18n:govoplan-campaign.cancel.77dfd213</Button><Button variant="primary" onClick={() => void saveOwner()} disabled={busy || !ownerId || ownerType === currentOwnerType && ownerId === currentOwnerId}>Propose transfer</Button></>}>
        <FormField label="i18n:govoplan-campaign.owner_type.6b86eacc"><select value={ownerType} onChange={(event) => {const next = event.target.value as TargetType;setOwnerType(next);setOwnerId("");}}><option value="user">i18n:govoplan-campaign.user.9f8a2389</option><option value="group">i18n:govoplan-campaign.group.171a0606</option></select></FormField>
        <FormField label="i18n:govoplan-campaign.owner.89ff3122">
          <ReferenceSelect
            value={ownerId}
            onChange={(value) => setOwnerId(value)}
            provider={ownerTargetProvider}
            selectedOption={targetMap.get(`${ownerType}:${ownerId}`) ?? null}
            disabled={busy}
            placeholder="i18n:govoplan-campaign.select.349ac8fb"
          />
        </FormField>
        <FormField label="Reason" help="Optional context shown to the proposed owner and retained in the decision history.">
          <textarea rows={3} maxLength={4000} value={ownerReason} onChange={(event) => setOwnerReason(event.target.value)} />
        </FormField>
        <FormField label="Expires after">
          <select value={ownerExpiryDays} onChange={(event) => setOwnerExpiryDays(Number(event.target.value))}>
            <option value={1}>1 day</option>
            <option value={3}>3 days</option>
            <option value={7}>7 days</option>
            <option value={14}>14 days</option>
            <option value={30}>30 days</option>
          </select>
        </FormField>
        <p className="muted small-note">The current owner remains responsible until the target accepts. The transfer is cancelled safely if it expires.</p>
      </Dialog>

      <Dialog open={requestOpen} className="campaign-access-dialog" title="Request campaign ownership" onClose={() => !busy && closeRequestDialog()} footer={<><Button onClick={closeRequestDialog} disabled={busy}>i18n:govoplan-campaign.cancel.77dfd213</Button><Button variant="primary" onClick={() => void requestOwnership()} disabled={busy || requestTargetType === "group" && !requestGroupId}>Submit request</Button></>}>
        <FormField label="Requested owner">
          <select value={requestTargetType} onChange={(event) => { setRequestTargetType(event.target.value as TargetType); setRequestGroupId(""); }}>
            <option value="user">My account</option>
            {canAcceptForGroup && auth.groups.length > 0 ? <option value="group">A group I manage</option> : null}
          </select>
        </FormField>
        {requestTargetType === "group" ? (
          <FormField label="Group">
            <select value={requestGroupId} onChange={(event) => setRequestGroupId(event.target.value)}>
              <option value="">Select a group</option>
              {auth.groups.map((group) => <option key={group.id} value={group.id}>{group.name}</option>)}
            </select>
          </FormField>
        ) : null}
        <FormField label="Reason" help="Optional context for the current owner.">
          <textarea rows={3} maxLength={4000} value={requestReason} onChange={(event) => setRequestReason(event.target.value)} />
        </FormField>
        <p className="muted small-note">The current owner must approve this request. You must then accept once more before ownership changes.</p>
      </Dialog>

      <Dialog open={shareOpen} className="campaign-access-dialog" title="i18n:govoplan-campaign.share_campaign.b605982b" onClose={() => !busy && closeShareDialog()} footer={<><Button onClick={closeShareDialog} disabled={busy}>i18n:govoplan-campaign.cancel.77dfd213</Button><Button variant="primary" onClick={() => void saveShare()} disabled={busy || !shareTargetId}>i18n:govoplan-campaign.save_share.bcf6ed94</Button></>}>
        <FormField label="i18n:govoplan-campaign.target_type.a45f8055"><select value={shareType} onChange={(event) => {const next = event.target.value as TargetType;setShareType(next);setShareTargetId("");}}><option value="user">i18n:govoplan-campaign.user.9f8a2389</option><option value="group">i18n:govoplan-campaign.group.171a0606</option></select></FormField>
        <FormField label="i18n:govoplan-campaign.user_or_group.53406ef0">
          <ReferenceSelect
            value={shareTargetId}
            onChange={(value) => setShareTargetId(value)}
            provider={shareTargetProvider}
            selectedOption={targetMap.get(`${shareType}:${shareTargetId}`) ?? null}
            disabled={busy}
            placeholder="i18n:govoplan-campaign.select.349ac8fb"
          />
        </FormField>
        <FormField label="i18n:govoplan-campaign.access.2f81a22d"><select value={sharePermission} onChange={(event) => setSharePermission(event.target.value as "read" | "write")}><option value="read">i18n:govoplan-campaign.can_view.1b3e4006</option><option value="write">i18n:govoplan-campaign.can_edit_and_operate.77acb15e</option></select></FormField>
      </Dialog>

      <Dialog open={accessExplanationOpen} className="campaign-access-dialog" title="i18n:govoplan-core.access_explanation.75ee7f62" onClose={() => { if (!accessExplanationLoading) { setAccessExplanationOpen(false); setAccessExplanation(null); } }} footer={<Button onClick={() => { setAccessExplanationOpen(false); setAccessExplanation(null); }} disabled={accessExplanationLoading}>i18n:govoplan-campaign.close.bbfa773e</Button>}>
        <ResourceAccessExplanation loading={accessExplanationLoading} explanation={accessExplanation} fallbackResourceLabel={campaign.name || campaign.external_id || campaign.id} />
      </Dialog>

      <ConfirmDialog open={Boolean(revokeTarget)} title="i18n:govoplan-campaign.remove_campaign_share.2c2d42eb" message="i18n:govoplan-campaign.remove_this_user_s_or_group_s_explicit_access_to.5ff07672" confirmLabel="i18n:govoplan-campaign.remove_share.69c932e1" tone="danger" busy={busy} onCancel={() => setRevokeTarget(null)} onConfirm={() => void revoke()} />
    </>);

}

function uniqueTargetIds(
  shares: readonly CampaignShare[],
  transfers: readonly OwnershipTransfer[],
  targetType: TargetType,
  ownerId?: string | null
): string[] {
  return [...new Set([
    ...(ownerId ? [ownerId] : []),
    ...shares
      .filter((share) => share.target_type === targetType)
      .map((share) => share.target_id),
    ...transfers.flatMap((transfer) => [
      ...(transfer.current_owner.type === targetType
        ? [transfer.current_owner.id]
        : []),
      ...(transfer.target_owner.type === targetType
        ? [transfer.target_owner.id]
        : [])
    ])
  ])];
}

type OwnershipUiAction = {
  id: "owner-approval" | "acceptance" | "decline" | "cancel";
  label: string;
  variant?: "primary" | "danger";
};

function ownershipTransferActions(
  transfer: OwnershipTransfer,
  context: {
    actorId: string;
    actorGroupIds: ReadonlySet<string>;
    canShare: boolean;
    canAcceptForGroup: boolean;
  }
): OwnershipUiAction[] {
  const controlsCurrent = controlsOwnershipSubject(
    transfer.current_owner,
    context
  );
  const controlsTarget = controlsOwnershipSubject(
    transfer.target_owner,
    context
  );
  if (transfer.status === "awaiting_owner_approval") {
    return [
      ...(controlsCurrent && context.canShare
        ? [
            {
              id: "owner-approval" as const,
              label: "Approve",
              variant: "primary" as const
            },
            {
              id: "decline" as const,
              label: "Decline",
              variant: "danger" as const
            }
          ]
        : []),
      ...(controlsTarget
        ? [
            {
              id: "cancel" as const,
              label: "Cancel request",
              variant: "danger" as const
            }
          ]
        : [])
    ];
  }
  if (transfer.status === "awaiting_target_acceptance") {
    return [
      ...(controlsTarget
        ? [
            {
              id: "acceptance" as const,
              label: "Accept ownership",
              variant: "primary" as const
            },
            {
              id: "decline" as const,
              label: "Decline",
              variant: "danger" as const
            }
          ]
        : []),
      ...(controlsCurrent && context.canShare
        ? [
            {
              id: "cancel" as const,
              label: "Cancel transfer",
              variant: "danger" as const
            }
          ]
        : [])
    ];
  }
  return [];
}

function controlsOwnershipSubject(
  subject: { type: string; id: string },
  context: {
    actorId: string;
    actorGroupIds: ReadonlySet<string>;
    canAcceptForGroup: boolean;
  }
): boolean {
  if (subject.type === "group") {
    return (
      context.canAcceptForGroup
      && context.actorGroupIds.has(subject.id)
    );
  }
  return subject.type === "user" && subject.id === context.actorId;
}

function ownershipSubjectLabel(
  subject: { type: string; id: string },
  targets: ReadonlyMap<string, ReferenceOption>
): string {
  return (
    targets.get(`${subject.type}:${subject.id}`)?.label
    || `${subject.type} ${subject.id}`
  );
}

function ownershipPendingParty(transfer: OwnershipTransfer): string {
  if (transfer.status === "awaiting_owner_approval") {
    return "Waiting for the current owner";
  }
  if (transfer.status === "awaiting_target_acceptance") {
    return "Waiting for the proposed owner";
  }
  if (transfer.status === "awaiting_recovery_approvals") {
    return `Waiting for recovery quorum (${transfer.approvals.length}/${transfer.required_approvals})`;
  }
  if (transfer.status === "recovery_scheduled") {
    return transfer.execute_after
      ? `Recovery available after ${formatOwnershipDate(transfer.execute_after)}`
      : "Recovery approval complete";
  }
  return transfer.decisions.at(-1)?.action.replace(/_/g, " ") || transfer.status;
}

function formatOwnershipDate(value: string): string {
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return value;
  return new Intl.DateTimeFormat(undefined, {
    dateStyle: "medium",
    timeStyle: "short"
  }).format(date);
}

async function resolveReferenceOptions(
  provider: ReferenceOptionProvider,
  values: readonly string[],
  signal: AbortSignal
): Promise<readonly ReferenceOption[]> {
  if (!values.length) return [];
  if (!provider.resolve) {
    return provider.search("", {
      selectedValues: values,
      limit: Math.min(200, Math.max(1, values.length)),
      signal
    });
  }
  return provider.resolve(values, {
    selectedValues: values,
    limit: Math.min(200, Math.max(1, values.length)),
    signal
  });
}
