import { useParams } from '@tanstack/react-router';
import { useOrder } from '../api/hooks';
import { StatusBadge, LoadingSpinner, Card } from '../components/ui';

/**
 * Lightweight JSON syntax highlighter for read-only display.
 * Returns React elements with colored spans for keys, strings, numbers, booleans, and null.
 */
function highlightJson(json: string): React.ReactNode {
  const parts: React.ReactNode[] = [];
  // Regex matches JSON tokens: strings, numbers, booleans, null, and structural chars
  const tokenRe = /("(?:\\.|[^"\\])*")\s*:|("(?:\\.|[^"\\])*")|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)|(\btrue\b|\bfalse\b)|(\bnull\b)|([{}[\],])/g;
  let lastIndex = 0;
  let match: RegExpExecArray | null;

  while ((match = tokenRe.exec(json)) !== null) {
    // Add any whitespace/text between tokens
    if (match.index > lastIndex) {
      parts.push(json.slice(lastIndex, match.index));
    }

    if (match[1]) {
      // Key (string followed by colon)
      parts.push(<span key={match.index} className="text-cyan-400">{match[1]}</span>);
      parts.push(':');
    } else if (match[2]) {
      // String value
      parts.push(<span key={match.index} className="text-green-400">{match[2]}</span>);
    } else if (match[3]) {
      // Number
      parts.push(<span key={match.index} className="text-yellow-300">{match[3]}</span>);
    } else if (match[4]) {
      // Boolean
      parts.push(<span key={match.index} className="text-purple-400">{match[4]}</span>);
    } else if (match[5]) {
      // Null
      parts.push(<span key={match.index} className="text-red-400">{match[5]}</span>);
    } else if (match[6]) {
      // Structural characters
      parts.push(<span key={match.index} className="text-gray-500">{match[6]}</span>);
    }

    lastIndex = match.index + match[0].length;
  }

  // Remaining text
  if (lastIndex < json.length) {
    parts.push(json.slice(lastIndex));
  }

  return <>{parts}</>;
}

export function OrderDetailPage() {
  const { id } = useParams({ from: '/orders/$id' });
  const { data: order, isLoading } = useOrder(id);

  if (isLoading || !order) return <LoadingSpinner />;

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-3">
        <h1 className="text-xl font-semibold text-gray-100">{order.ticker}</h1>
        <StatusBadge status={order.side} />
        <StatusBadge status={order.status} />
      </div>

      <Card>
        <dl className="grid grid-cols-2 gap-x-8 gap-y-3 text-sm sm:grid-cols-4">
          <div><dt className="text-gray-500">Type</dt><dd className="text-gray-200">{order.order_type}</dd></div>
          <div><dt className="text-gray-500">Quantity</dt><dd className="text-gray-200">{order.quantity}</dd></div>
          <div><dt className="text-gray-500">Limit Price</dt><dd className="text-gray-200">{order.limit_price != null ? `$${order.limit_price.toFixed(2)}` : '—'}</dd></div>
          <div><dt className="text-gray-500">Fill Price</dt><dd className="text-gray-200">{order.fill_price != null ? `$${order.fill_price.toFixed(2)}` : '—'}</dd></div>
          <div><dt className="text-gray-500">Fill Qty</dt><dd className="text-gray-200">{order.fill_quantity ?? '—'}</dd></div>
          <div><dt className="text-gray-500">Broker Order</dt><dd className="truncate font-mono text-xs text-gray-400">{order.broker_order_id ?? '—'}</dd></div>
          <div><dt className="text-gray-500">Idempotency Key</dt><dd className="truncate font-mono text-xs text-gray-400">{order.idempotency_key ?? '—'}</dd></div>
          <div><dt className="text-gray-500">Created</dt><dd className="text-gray-300">{new Date(order.created_at).toLocaleString()}</dd></div>
        </dl>
      </Card>

      {/* Decision Trace */}
      {order.decision_trace && Object.keys(order.decision_trace).length > 0 && (
        <Card>
          <h2 className="mb-2 text-sm font-medium text-gray-400">Decision Trace</h2>
          <pre className="overflow-x-auto rounded bg-surface-950 p-3 text-xs leading-relaxed">
            {highlightJson(JSON.stringify(order.decision_trace, null, 2))}
          </pre>
        </Card>
      )}

      {/* Order Events Timeline */}
      <Card>
        <h2 className="mb-3 text-sm font-medium text-gray-400">Events ({order.events.length})</h2>
        {order.events.length === 0 ? (
          <p className="text-sm text-gray-500">No events</p>
        ) : (
          <div className="space-y-2">
            {order.events.map((ev) => (
              <div key={ev.id} className="flex items-start gap-3 rounded border border-surface-700 bg-surface-950 p-2">
                <StatusBadge status={ev.event_type} />
                <div className="flex-1">
                  <div className="text-xs text-gray-400">{new Date(ev.created_at).toLocaleString()}</div>
                  {ev.data ? (
                    <pre className="mt-1 text-xs text-gray-500">{JSON.stringify(ev.data, null, 2) ?? ''}</pre>
                  ) : null}
                </div>
              </div>
            ))}
          </div>
        )}
      </Card>

      {/* Audit Trail */}
      {order.audit_trail && (order.audit_trail as unknown[]).length > 0 && (
        <Card>
          <h2 className="mb-3 text-sm font-medium text-gray-400">Audit Trail</h2>
          <div className="space-y-1">
            {(order.audit_trail as Array<Record<string, unknown>>).map((entry, i) => (
              <div key={i} className="flex gap-3 text-xs">
                <span className="text-gray-500">{entry.created_at ? new Date(String(entry.created_at)).toLocaleString() : ''}</span>
                <span className="text-gray-400">{String(entry.event_type)}</span>
                <span className="text-gray-300">{String(entry.description)}</span>
              </div>
            ))}
          </div>
        </Card>
      )}
    </div>
  );
}
