"use client";

import {
  getMemberPointsBalance,
  type CoreMemberPoints,
} from "@/lib/features/members/query";
import { ActionIcon, Badge, Group, Text, Tooltip } from "@mantine/core";
import { IconCoins } from "@tabler/icons-react";
import { useState } from "react";

/**
 * Viewpoint points for an account, fetched on click.
 *
 * Its own component so it can sit on the page header line rather than inside the
 * overview strip: the figure belongs with the account identity, and keeping the
 * fetch state here means the header doesn't have to own it.
 *
 * Renders nothing without a membership number — that is how the caller says
 * "this user has no `can_view_points` capability".
 */
export function MemberPointsControl({
  membershipNumber,
}: {
  membershipNumber?: string;
}) {
  const [points, setPoints] = useState<CoreMemberPoints | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  if (!membershipNumber) return null;

  const load = async () => {
    setLoading(true);
    setError(null);
    const response = await getMemberPointsBalance(membershipNumber);
    setLoading(false);
    if (response?.success && response.data) {
      setPoints(response.data as CoreMemberPoints);
    } else {
      setError(response?.message || "Viewpoint did not return points");
    }
  };

  return (
    <Group gap={8} wrap="nowrap">
      {points ? (
        <Badge variant="light" radius={4} leftSection={<IconCoins size={12} />}>
          {points.balance.toLocaleString()} points ·{" "}
          {points.entitlements.length} entitlement(s)
        </Badge>
      ) : null}
      {error ? (
        <Text fz={12} c="red">
          {error}
        </Text>
      ) : null}
      <Tooltip
        label={points ? "Refresh Viewpoint points" : "Fetch Viewpoint points"}
      >
        <ActionIcon
          variant="light"
          size="lg"
          radius="md"
          loading={loading}
          onClick={() => void load()}
          aria-label="Fetch Viewpoint points"
        >
          <IconCoins size={18} />
        </ActionIcon>
      </Tooltip>
    </Group>
  );
}
