import { useT } from '@/lib/i18n/react';
import { Button } from '@/components/ui/primitives/Button';
import { LabelWithTooltip } from '@/components/ui/primitives/LabelWithTooltip';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { formatAgorotDisplay, formatAgorotShekels, formatAgorotPlain } from '@/lib/money.js';
import { type AffiliateConnectStatusOrNull } from '@/lib/enums/affiliate-connect-status';
import { authenticatedFetch } from '@/lib/authenticated-fetch';

type Props = {
  pendingAgorot: number;
  maturedAgorot: number;
  minWithdrawalAgorot: number;
  connectStatus: AffiliateConnectStatusOrNull;
};

export function AffiliateWithdrawPanel({
  pendingAgorot,
  maturedAgorot,
  minWithdrawalAgorot,
  connectStatus,
}: Props) {
  const t = useT('affiliate');
  const queryClient = useQueryClient();

  const withdrawAmountDisplay = formatAgorotPlain(maturedAgorot);

  const withdraw = useMutation({
    mutationFn: async () => {
      const res = await authenticatedFetch('/api/affiliate/withdraw', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ amountAgorot: maturedAgorot }),
      });
      const payload = await res.json();
      if (!res.ok) throw new Error('Affiliate withdrawal request failed');
      return payload;
    },
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ['affiliate-wallet'] });
    },
  });

  const canWithdraw =
    connectStatus === 'active' &&
    maturedAgorot > 0 &&
    maturedAgorot >= minWithdrawalAgorot &&
    !withdraw.isSuccess;

  return (
    <section
      aria-labelledby="withdraw-heading"
      className="rounded-xl border border-(--color-border) bg-(--color-surface) p-5"
    >
      <h2 id="withdraw-heading" className="mb-4 text-lg font-semibold">
        {t('withdraw_heading')}
      </h2>

      <dl className="mb-5 grid grid-cols-2 gap-3">
        <div>
          <dt className="text-sm text-(--color-text-muted)">
            <LabelWithTooltip
              label={t('withdraw_balance_pending')}
              tooltip={t('tooltip_balance_pending')}
            />
          </dt>
          <dd className="mt-0.5 text-xl font-semibold tabular-nums">
            {formatAgorotShekels(pendingAgorot)}
          </dd>
        </div>
        <div>
          <dt className="text-sm text-(--color-text-muted)">
            <LabelWithTooltip
              label={t('withdraw_balance_available')}
              tooltip={t('tooltip_balance_available')}
            />
          </dt>
          <dd className="mt-0.5 text-xl font-semibold tabular-nums">
            {(() => {
              const display = formatAgorotDisplay(maturedAgorot);
              if (typeof display === 'object' && display.isDebt) {
                const amount = formatAgorotPlain(display.debtAgorot);
                return (
                  <span className="text-(--color-text-muted)">
                    {t('balance_debt_label')}
                    <span className="mt-0.5 block text-xs">
                      {t('balance_debt_detail').replace('{{amount}}', amount)}
                    </span>
                  </span>
                );
              }
              return <span>{display as string}</span>;
            })()}
          </dd>
        </div>
      </dl>

      {!canWithdraw && maturedAgorot < minWithdrawalAgorot && connectStatus !== null && (
        <p className="mb-3 text-sm text-(--color-text-muted)">
          {t('withdraw_min_notice')}: {formatAgorotShekels(minWithdrawalAgorot)}
        </p>
      )}

      {withdraw.isSuccess && (
        <p role="status" className="mb-3 text-sm text-(--color-success)">
          {t('withdraw_success').replace('{{amount}}', withdrawAmountDisplay)}
        </p>
      )}
      {withdraw.isError && (
        <p role="alert" className="mb-3 text-sm text-(--color-error)">
          {t('withdraw_error')}
        </p>
      )}

      <Button
        variant="primary"
        size="md"
        disabled={!canWithdraw || withdraw.isPending}
        loading={withdraw.isPending}
        onClick={() => withdraw.mutate()}
      >
        {withdraw.isPending
          ? t('withdraw_processing')
          : t('withdraw_cta').replace('{{amount}}', withdrawAmountDisplay)}
      </Button>
    </section>
  );
}
