'use client';
/**
 * FraudActionBar — four resolution actions for a fraud_events row.
 * Placed in the evidence drawer footer.
 *
 * Actions:
 *   Release — always available; EARN clears quarantine, WITHDRAW approves payout.
 *   Reject & Clawback — always available; requires confirm modal showing ₪ amount.
 *   Suspend Affiliate — always available.
 *   Dismiss — flag-only, no financial effect.
 *
 * Each action requires reason ≥5 chars (inline validation before submit).
 * Reject confirm modal uses AlertDialog composition (focus-trapped by Radix).
 */
import { useState, type ReactNode } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { useT } from '@/lib/i18n/react';
import { Button } from '@/components/ui/primitives/Button';
import { Input } from '@/components/ui/primitives/Input';
import {
  AlertDialog,
  AlertDialogContent,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogAction,
  AlertDialogCancel,
} from '@/components/ui/overlays/AlertDialog';
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/overlays/Tooltip';
import { getCsrfToken } from '@/lib/csrf';
import { captureCaught } from '@/lib/observability';
import { fetchWithRefresh } from '@/lib/api/refresh-on-401';
import { agorotToShekels } from '@/lib/money';

// ─── Types ────────────────────────────────────────────────────────────────────

export interface FraudActionBarProps {
  /** The fraud event id (`fraud_events.id`). */
  eventId: string;
  /** The decision point — affects release semantics (for display only). */
  decisionPoint: 'signup' | 'earn' | 'withdraw';
  /** The triggering action — `flag` shows the Dismiss button. */
  fraudAction: 'block' | 'hold' | 'flag';
  /** Amount at stake in agorot — pre-filled in the Reject confirm modal. */
  amountAgorot: number;
  /** Called after a successful resolve so the parent can refresh/close. */
  onResolved: () => void;
}

type ActionStep = 'idle' | 'release' | 'reject_clawback' | 'reject_confirm' | 'suspend' | 'dismiss';

// ─── Component ────────────────────────────────────────────────────────────────

export function FraudActionBar({
  eventId,
  fraudAction,
  amountAgorot,
  onResolved,
}: FraudActionBarProps) {
  const t = useT('admin_affiliates');
  const qc = useQueryClient();

  const [step, setStep] = useState<ActionStep>('idle');
  const [reason, setReason] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // agorot → whole-shekel numeric; template owns the ₪ symbol (fraud_reject_confirm_body: '...₪{{amount}}...')
  const amountNis = String(Math.round(agorotToShekels(amountAgorot)));
  const amountDescId = `reject-amount-${eventId}`;
  const reasonValid = reason.trim().length >= 5;

  // Show reason input for all intermediate steps except reject_confirm
  const showReasonInput = step !== 'idle' && step !== 'reject_confirm';

  async function submitAction(action: 'release' | 'reject_clawback' | 'suspend' | 'dismiss') {
    setSubmitting(true);
    setError(null);
    try {
      const body: Record<string, unknown> = { action, reason: reason.trim() };
      if (action === 'reject_clawback') {
        body.confirm_amount_agorot = amountAgorot;
      }
      const res = await fetchWithRefresh(`/api/admin/affiliates/fraud/events/${eventId}/resolve`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'x-csrf-token': getCsrfToken(),
        },
        body: JSON.stringify(body),
      });
      if (!res.ok) {
        const json = await res.json().catch((err) => {
          captureCaught(err, { scope: 'features.fraud-action-bar.parse-error' });
          return {};
        });
        setError((json as { error?: string }).error ?? t('fraud_error_generic'));
        return;
      }
      // Invalidate the fraud queue and stats so the dashboard refreshes
      void qc.invalidateQueries({ queryKey: ['fraud-events'] });
      void qc.invalidateQueries({ queryKey: ['fraud-stats'] });
      onResolved();
    } catch (err) {
      captureCaught(err, { scope: 'features.fraud-action-bar.submit' });
      setError(t('fraud_error_network'));
    } finally {
      setSubmitting(false);
      if (step !== 'reject_confirm') {
        setStep('idle');
        setReason('');
      }
    }
  }

  function cancel() {
    setStep('idle');
    setReason('');
    setError(null);
  }

  return (
    <div className="space-y-3 border-t border-(--color-border) bg-(--color-surface-raised) px-4 py-3">
      {/* Error banner */}
      {error && (
        <p role="alert" className="text-xs text-(--color-error)">
          {error}
        </p>
      )}

      {/* Step: idle — show four action buttons */}
      {step === 'idle' && (
        <TooltipProvider>
          <div className="flex flex-wrap gap-2">
            <ActionTooltip label={t('fraud_action_release_tooltip')}>
              <Button size="sm" variant="primary" onClick={() => setStep('release')}>
                {t('fraud_action_release')}
              </Button>
            </ActionTooltip>
            <ActionTooltip label={t('fraud_action_reject_clawback_tooltip')}>
              <Button size="sm" variant="danger" onClick={() => setStep('reject_clawback')}>
                {t('fraud_action_reject_clawback')}
              </Button>
            </ActionTooltip>
            <ActionTooltip label={t('fraud_action_suspend_tooltip')}>
              <Button size="sm" variant="secondary" onClick={() => setStep('suspend')}>
                {t('fraud_action_suspend')}
              </Button>
            </ActionTooltip>
            {fraudAction === 'flag' && (
              <ActionTooltip label={t('fraud_action_dismiss_tooltip')}>
                <Button size="sm" variant="ghost" onClick={() => setStep('dismiss')}>
                  {t('fraud_action_dismiss')}
                </Button>
              </ActionTooltip>
            )}
          </div>
        </TooltipProvider>
      )}

      {/* Step: reason input (release / reject_clawback / suspend / dismiss) */}
      {showReasonInput && (
        <div className="space-y-2">
          <label htmlFor={`fraud-reason-${eventId}`} className="sr-only">
            {t('fraud_action_reason_placeholder')}
          </label>
          <Input
            id={`fraud-reason-${eventId}`}
            placeholder={t('fraud_action_reason_placeholder')}
            value={reason}
            onChange={(e) => setReason(e.target.value)}
            aria-label={t('fraud_action_reason_placeholder')}
            aria-required="true"
            aria-invalid={reason.trim().length > 0 && !reasonValid}
            minLength={5}
            maxLength={500}
            disabled={submitting}
          />
          {reason.trim().length > 0 && !reasonValid && (
            <p role="alert" aria-live="polite" className="text-xs text-(--color-error)">
              {t('fraud_action_reason_min')}
            </p>
          )}
          <div className="flex gap-2">
            <Button
              size="sm"
              variant="primary"
              disabled={!reasonValid || submitting}
              onClick={() => {
                if (step === 'reject_clawback') {
                  setStep('reject_confirm');
                } else {
                  void submitAction(step as 'release' | 'suspend' | 'dismiss');
                }
              }}
            >
              {t('fraud_action_continue')}
            </Button>
            <Button size="sm" variant="ghost" onClick={cancel} disabled={submitting}>
              {t('fraud_action_cancel')}
            </Button>
          </div>
        </div>
      )}

      {/* Step: reject_confirm — AlertDialog for destructive Reject & Clawback */}
      {step === 'reject_confirm' && (
        <AlertDialog
          open
          onOpenChange={(open) => {
            if (!open) setStep('reject_clawback');
          }}
        >
          <AlertDialogContent aria-describedby={amountDescId}>
            <AlertDialogHeader>
              <AlertDialogTitle>{t('fraud_reject_confirm_title')}</AlertDialogTitle>
              <AlertDialogDescription id={amountDescId}>
                {t('fraud_reject_confirm_body').replace('{{amount}}', String(amountNis))}
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogAction
                disabled={submitting}
                onClick={(e) => {
                  e.preventDefault();
                  void submitAction('reject_clawback').then(() => {
                    setStep('idle');
                    setReason('');
                  });
                }}
                className="bg-danger-600 hover:bg-danger-700 focus-visible:ring-danger-500 text-white"
              >
                {t('fraud_reject_confirm_cta').replace('{{amount}}', String(amountNis))}
              </AlertDialogAction>
              <AlertDialogCancel disabled={submitting} onClick={() => setStep('reject_clawback')}>
                {t('fraud_action_cancel')}
              </AlertDialogCancel>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      )}
    </div>
  );
}

function ActionTooltip({ label, children }: { label: string; children: ReactNode }) {
  return (
    <Tooltip>
      <TooltipTrigger asChild>{children}</TooltipTrigger>
      <TooltipContent>{label}</TooltipContent>
    </Tooltip>
  );
}
