'use client';

import { useQuery } from '@tanstack/react-query';
import { ArrowRight, Plus, Wallet } from 'lucide-react';
import Link from 'next/link';

import { buttonVariants } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { ApiError, api } from '@/lib/api-client';
import { formatMoney } from '@/lib/money';
import { queryKeys } from '@/lib/query-keys';
import { cn } from '@/lib/utils';

/** Always-dark wallet balance card. Data fetching is unchanged from the original dashboard. */
export function WalletCard({ currency }: { currency?: string }) {
  const wallet = useQuery({
    queryKey: queryKeys.wallet,
    queryFn: () => api<{ balanceMinor: number; currency: string; lowBalance: boolean }>('/wallet'),
    retry: false,
  });
  const forbidden = wallet.error instanceof ApiError && wallet.error.status === 403;

  return (
    <section
      aria-labelledby="wallet-card-title"
      className="relative isolate flex h-full min-h-[240px] flex-col overflow-hidden rounded-xl bg-[linear-gradient(140deg,rgb(var(--ink-from)),rgb(var(--brand-to)))] p-6 text-primary-foreground shadow-md"
    >
      {/* Decorative: mesh glow and a faint card-like ring pattern */}
      <div className="pointer-events-none absolute inset-0 -z-10 bg-mesh opacity-40 [--accent:255_255_255] [--primary:167_139_250]" aria-hidden="true" />
      <div className="pointer-events-none absolute -bottom-16 -right-12 -z-10 h-56 w-56 rounded-full border-[28px] border-primary-foreground/[0.06]" aria-hidden="true" />
      <div className="pointer-events-none absolute -bottom-6 right-20 -z-10 h-24 w-24 rounded-full border-[14px] border-primary-foreground/[0.05]" aria-hidden="true" />

      <div className="flex items-center gap-3">
        <span className="grid h-9 w-9 place-items-center rounded-lg bg-primary-foreground/15 ring-1 ring-inset ring-primary-foreground/20">
          <Wallet className="h-[18px] w-[18px]" aria-hidden="true" />
        </span>
        <h2 id="wallet-card-title" className="text-[13px] font-medium text-primary-foreground/70">
          Wallet balance
        </h2>
      </div>

      {wallet.isLoading ? (
        <div className="mt-5 grid gap-3">
          <Skeleton className="h-11 w-40 bg-primary-foreground/10" />
          <Skeleton className="h-6 w-24 rounded-pill bg-primary-foreground/10" />
        </div>
      ) : null}

      {forbidden ? <p className="mt-5 text-small text-primary-foreground/80">You do not have access to the wallet.</p> : null}

      {wallet.error !== null && !forbidden ? (
        <div className="mt-5 grid justify-items-start gap-3" role="alert">
          <p className="text-small text-primary-foreground/80">The wallet could not be loaded.</p>
          <button
            type="button"
            onClick={() => void wallet.refetch()}
            className="rounded-md border border-primary-foreground/30 px-3 py-1.5 text-small font-semibold transition-colors hover:bg-primary-foreground/10"
          >
            Retry
          </button>
        </div>
      ) : null}

      {wallet.data !== undefined ? (
        <>
          <p className="mt-4 font-display text-display-lg tabular-nums text-primary-foreground">
            {formatMoney(wallet.data.balanceMinor, wallet.data.currency || currency || 'USD')}
          </p>
          {(() => {
            const state = wallet.data.balanceMinor <= 0 ? 'empty' : wallet.data.lowBalance ? 'low' : 'healthy';
            return (
              <span
                className={cn(
                  'mt-3 inline-flex w-fit items-center gap-1.5 rounded-pill px-2.5 py-1 text-caption font-semibold ring-1 ring-inset',
                  state === 'healthy' && 'bg-success/20 text-success ring-success/30',
                  state === 'low' && 'bg-warning/20 text-warning ring-warning/30',
                  state === 'empty' && 'bg-danger/20 text-danger ring-danger/30',
                )}
              >
                <span className={cn('h-1.5 w-1.5 rounded-full', state === 'healthy' ? 'bg-success' : state === 'low' ? 'bg-warning' : 'bg-danger')} aria-hidden="true" />
                {state === 'healthy' ? 'Healthy' : state === 'low' ? 'Low balance' : 'Empty, top up to ship'}
              </span>
            );
          })()}
          <div className="mt-auto flex flex-wrap gap-2 pt-6">
            <Link
              href="/wallet"
              className={cn(buttonVariants({ size: 'sm' }), 'bg-primary-foreground bg-none text-[rgb(var(--ink-from))] shadow-sm hover:bg-primary-foreground/90')}
            >
              <Plus className="h-4 w-4" aria-hidden="true" />
              Top up
            </Link>
            <Link
              href="/wallet"
              className={cn(buttonVariants({ variant: 'outline', size: 'sm' }), 'border-primary-foreground/30 bg-primary-foreground/10 text-primary-foreground hover:bg-primary-foreground/15')}
            >
              View ledger
              <ArrowRight className="h-3.5 w-3.5" aria-hidden="true" />
            </Link>
          </div>
        </>
      ) : null}
    </section>
  );
}
