'use client';
/**
 * FraudEvidenceDrawer — inline-expand evidence panel (no navigation).
 *
 * Renders under a fraud-queue row as role="region" (expand toggle owns aria-expanded).
 * Self-fetches evidence via react-query when eventId is provided.
 * Shows: identity signals · adapter evidence · linked events · affiliate history.
 *
 * PII note: visitor_id_referee, ip_hash_referee are hashed fingerprints; email_canonical_index
 * is the indexed canonical form (not raw email). detail jsonb is rendered verbatim — adapters
 * are expected to write only match_field / metadata, never raw PII.
 */
import { useEffect, useRef } from 'react';
import { useQuery } from '@tanstack/react-query';
import { QueryBoundary } from '@platform-modules/ui-primitives';
import { useT } from '@/lib/i18n/react';
import { Badge } from '@/components/ui/primitives/Badge';
import { IconButton } from '@/components/ui/primitives/IconButton';
import { X } from 'lucide-react';
import { cn } from '@/lib/cn';
import { FraudActionBar } from './FraudActionBar';
import { formatDate } from '@/lib/format';
import { Skeleton } from '@/components/ui/feedback/Skeleton';

export interface FraudEvidence {
  id: string;
  detail: Record<string, unknown>;
  codes: string[];
  adapter: string;
  visitor_id_referee: string | null;
  ip_hash_referee: string | null;
  email_canonical_index: string | null;
  ip_seen_count: number | null;
  linked_events: Array<{ id: string; action: string; adapter: string; ts: string }> | null;
  affiliate_history: Array<{ action: string; ts: string; reason: string | null }> | null;
}

export interface FraudDrawerActionProps {
  decisionPoint: 'signup' | 'earn' | 'withdraw';
  fraudAction: 'block' | 'hold' | 'flag';
  amountAgorot: number;
}

interface Props {
  eventId: string | null;
  onClose: () => void;
  className?: string;
  actionProps?: FraudDrawerActionProps;
}

function EvidenceContent({
  evidence,
  onClose,
  actionProps,
  className,
}: {
  evidence: FraudEvidence;
  onClose: () => void;
  actionProps?: FraudDrawerActionProps;
  className?: string;
}) {
  const regionId = `fraud-evidence-${evidence.id}`;
  const headingId = `${regionId}-heading`;
  const t = useT('admin_affiliates');
  const regionRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const first = regionRef.current?.querySelector<HTMLElement>(
      'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',
    );
    first?.focus();
  }, []);

  return (
    <div
      ref={regionRef}
      id={regionId}
      role="region"
      aria-label={t('fraud_drawer_identity_signals')}
      aria-labelledby={headingId}
      className={cn(
        'border-t border-(--color-border) bg-(--color-surface-raised) px-4 py-4',
        className,
      )}
    >
      <div className="mb-3 flex items-center justify-between">
        <span id={headingId} className="text-sm font-semibold text-(--color-text)">
          {t('fraud_drawer_identity_signals')}
        </span>
        <IconButton
          variant="ghost"
          size="sm"
          aria-label={t('fraud_expand_close')}
          onClick={onClose}
          icon={<X className="h-4 w-4" aria-hidden />}
        />
      </div>

      <section className="mb-4">
        <h3 className="mb-2 text-xs font-semibold tracking-wide text-(--color-text-subtle) uppercase">
          {t('fraud_drawer_identity_signals')}
        </h3>
        <dl className="grid grid-cols-2 gap-x-4 gap-y-1 text-sm">
          {evidence.visitor_id_referee && (
            <>
              <dt className="text-(--color-text-subtle)">{t('fraud_drawer_device')}</dt>
              <dd>
                <code className="font-mono">…{evidence.visitor_id_referee.slice(-8)}</code>
              </dd>
            </>
          )}
          {evidence.ip_hash_referee && (
            <>
              <dt className="text-(--color-text-subtle)">{t('fraud_drawer_ip')}</dt>
              <dd>
                <code className="font-mono">…{evidence.ip_hash_referee.slice(-8)}</code>
                {evidence.ip_seen_count != null && evidence.ip_seen_count > 0 && (
                  <span className="ms-2 text-xs text-(--color-text-subtle)">
                    {t('fraud_drawer_seen_n_times').replace(
                      '{{count}}',
                      String(evidence.ip_seen_count),
                    )}
                  </span>
                )}
              </dd>
            </>
          )}
          {evidence.email_canonical_index && (
            <>
              <dt className="text-(--color-text-subtle)">{t('fraud_drawer_email_canonical')}</dt>
              <dd className="font-mono text-xs">{evidence.email_canonical_index}</dd>
            </>
          )}
        </dl>
      </section>

      {Object.keys(evidence.detail).length > 0 && (
        <section className="mb-4">
          <h3 className="mb-2 text-xs font-semibold tracking-wide text-(--color-text-subtle) uppercase">
            {t('fraud_drawer_adapter_evidence')}
          </h3>
          <dl className="grid grid-cols-2 gap-x-4 gap-y-1 text-sm">
            {Object.entries(evidence.detail).map(([k, v]) => (
              <>
                <dt key={`dt-${k}`} className="text-(--color-text-subtle)">
                  {k}
                </dt>
                <dd key={`dd-${k}`} className="font-mono text-xs break-all">
                  {String(v)}
                </dd>
              </>
            ))}
          </dl>
        </section>
      )}

      {evidence.linked_events && evidence.linked_events.length > 0 && (
        <section className="mb-4">
          <h3 className="mb-2 text-xs font-semibold tracking-wide text-(--color-text-subtle) uppercase">
            {t('fraud_drawer_linked_events')} ({evidence.linked_events.length})
          </h3>
          <ul className="space-y-1">
            {evidence.linked_events.map((le) => (
              <li key={le.id} className="flex items-center gap-2 text-xs text-(--color-text)">
                <Badge tone="neutral" size="sm">
                  {le.action}
                </Badge>
                <span>{le.adapter}</span>
                <span className="text-(--color-text-subtle)">{formatDate(le.ts, 'he')}</span>
              </li>
            ))}
          </ul>
        </section>
      )}

      {evidence.affiliate_history && evidence.affiliate_history.length > 0 && (
        <section>
          <h3 className="mb-2 text-xs font-semibold tracking-wide text-(--color-text-subtle) uppercase">
            {t('fraud_drawer_affiliate_history')}
          </h3>
          <ul className="space-y-1">
            {evidence.affiliate_history.map((h) => (
              <li key={`${h.ts}-${h.action}`} className="flex items-center gap-2 text-xs">
                <Badge tone="neutral" size="sm">
                  {h.action}
                </Badge>
                <span className="text-(--color-text-subtle)">{formatDate(h.ts, 'he')}</span>
                {h.reason && (
                  <span className="max-w-[20ch] truncate text-(--color-text-subtle)">
                    {h.reason}
                  </span>
                )}
              </li>
            ))}
          </ul>
        </section>
      )}

      {actionProps && (
        <FraudActionBar
          eventId={evidence.id}
          decisionPoint={actionProps.decisionPoint}
          fraudAction={actionProps.fraudAction}
          amountAgorot={actionProps.amountAgorot}
          onResolved={onClose}
        />
      )}
    </div>
  );
}

function FraudEvidenceDrawerSkeleton({ className }: { className?: string }) {
  return (
    <div
      aria-hidden="true"
      role="presentation"
      className={cn(
        'border-t border-(--color-border) bg-(--color-surface-raised) px-4 py-4',
        className,
      )}
    >
      <div className="mb-3 flex items-center justify-between">
        <Skeleton className="h-5 w-36" />
        <Skeleton className="h-8 w-8 rounded-md" />
      </div>
      <section className="mb-4">
        <Skeleton className="mb-2 h-4 w-28" />
        <div className="grid grid-cols-2 gap-x-4 gap-y-2">
          {Array.from({ length: 6 }).map((_, index) => (
            <Skeleton key={index} className="h-4 w-full" />
          ))}
        </div>
      </section>
      <section className="mb-4">
        <Skeleton className="mb-2 h-4 w-32" />
        <div className="grid grid-cols-2 gap-x-4 gap-y-2">
          {Array.from({ length: 4 }).map((_, index) => (
            <Skeleton key={index} className="h-4 w-full" />
          ))}
        </div>
      </section>
      <section className="mb-4">
        <Skeleton className="mb-2 h-4 w-32" />
        <div className="space-y-2">
          {Array.from({ length: 3 }).map((_, index) => (
            <div key={index} className="flex items-center gap-2">
              <Skeleton className="h-5 w-16 rounded-full" />
              <Skeleton className="h-4 w-24" />
              <Skeleton className="h-4 w-28" />
            </div>
          ))}
        </div>
      </section>
      <section>
        <Skeleton className="mb-2 h-4 w-36" />
        <div className="space-y-2">
          {Array.from({ length: 3 }).map((_, index) => (
            <div key={index} className="flex items-center gap-2">
              <Skeleton className="h-5 w-16 rounded-full" />
              <Skeleton className="h-4 w-24" />
              <Skeleton className="h-4 w-20" />
            </div>
          ))}
        </div>
      </section>
    </div>
  );
}

export function FraudEvidenceDrawer({ eventId, onClose, className, actionProps }: Props) {
  const t = useT('admin_affiliates');

  const evidenceQuery = useQuery<{ evidence: FraudEvidence }>({
    queryKey: ['fraud-evidence', eventId],
    queryFn: async () => {
      const res = await fetch(`/api/admin/affiliates/fraud/events/${eventId}`);
      if (!res.ok) throw new Error(await res.text());
      const json = (await res.json()) as { data: { evidence: FraudEvidence } };
      return json.data;
    },
    enabled: !!eventId,
    staleTime: 30_000,
  });

  if (!eventId) return null;

  return (
    <QueryBoundary
      query={evidenceQuery}
      skeleton={<FraudEvidenceDrawerSkeleton className={className} />}
      errorFallback={() => (
        <div
          id={`fraud-evidence-${eventId}`}
          role="region"
          aria-label={t('fraud_drawer_identity_signals')}
          className={cn(
            'flex items-center justify-between border-t border-(--color-border) bg-(--color-surface-raised) px-4 py-4',
            className,
          )}
        >
          <p className="text-sm text-(--color-text-subtle)">{t('fraud_drawer_error')}</p>
          <IconButton
            variant="ghost"
            size="sm"
            aria-label={t('fraud_expand_close')}
            onClick={onClose}
            icon={<X className="h-4 w-4" aria-hidden />}
          />
        </div>
      )}
    >
      {(resolved) => (
        <EvidenceContent
          evidence={resolved.evidence}
          onClose={onClose}
          actionProps={actionProps}
          className={className}
        />
      )}
    </QueryBoundary>
  );
}
