'use client';

import { formatPrice } from '@alqove/shared';
import { useBalance } from '@/lib/queries/use-balance';

interface Props {
  storeId: string;
}

// SSR-safe: pin locale + UTC so server and client render the same string.
const PAYOUT_DATE_FORMATTER = new Intl.DateTimeFormat('en-US', {
  month: 'short',
  day: 'numeric',
  timeZone: 'UTC',
});

function formatPayoutDate(iso: string): string {
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) return '';
  return PAYOUT_DATE_FORMATTER.format(date);
}

export function SellerBalanceWidget({ storeId }: Props) {
  const { data, isLoading, isError } = useBalance(storeId);

  if (isLoading) {
    return (
      <div
        data-testid="seller-balance-widget-loading"
        className="rounded-md border border-forest/20 bg-bone p-4"
      >
        <div className="text-xs uppercase tracking-wide text-forest/70">Balance</div>
        <div className="mt-2 space-y-2">
          <div className="h-5 w-48 animate-pulse rounded bg-forest/10" />
          <div className="h-5 w-56 animate-pulse rounded bg-forest/10" />
        </div>
      </div>
    );
  }

  if (isError || !data) {
    return (
      <div className="rounded-md border border-forest/20 bg-bone p-4">
        <div className="text-xs uppercase tracking-wide text-forest/70">Balance</div>
        <div className="mt-2 text-sm text-terracotta/80">Couldn&apos;t load balance.</div>
      </div>
    );
  }

  const balance = data.data;
  const payoutDate = formatPayoutDate(balance.next_payout_date);

  return (
    <div className="rounded-md border border-forest/20 bg-bone p-4">
      <div className="text-xs uppercase tracking-wide text-forest/70">Balance</div>
      <dl className="mt-2 space-y-1.5 text-sm">
        <div className="flex flex-wrap items-baseline gap-x-2">
          <dt className="font-medium text-ink">Available:</dt>
          <dd className="text-ink">
            <span className="font-semibold">{formatPrice(balance.available_cents)}</span>
            {payoutDate ? (
              <span className="text-ink/60"> (paying out {payoutDate})</span>
            ) : null}
          </dd>
        </div>
        <div className="flex flex-wrap items-baseline gap-x-2">
          <dt className="font-medium text-ink">Pending:</dt>
          <dd className="text-ink">
            <span className="font-semibold">{formatPrice(balance.pending_cents)}</span>
            <span className="text-ink/60"> (releasing as orders deliver)</span>
          </dd>
        </div>
      </dl>
    </div>
  );
}
