All files / src/components/features/admin/monitoring/MetricsSummary index.tsx

0% Statements 0/268
100% Branches 0/0
0% Functions 0/1
0% Lines 0/268

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
'use client';

import React, { useState, useEffect, useRef } from 'react';

export interface MetricsSummaryProps {
  /** Total requests in the time period */
  totalRequests: number;
  /** Success rate as percentage */
  successRate: number;
  /** Average duration in milliseconds */
  avgDuration: number;
  /** Number of errors */
  errorCount: number;
  /** Enable animations for value changes */
  animated?: boolean;
}

/**
 * Hook to track value changes and trigger animations
 */
function useValueChange(value: number, threshold: number = 0.01) {
  const previousValueRef = useRef<number>(value);
  const [changeDirection, setChangeDirection] = useState<'up' | 'down' | null>(null);
  const [isAnimating, setIsAnimating] = useState(false);

  useEffect(() => {
    const diff = value - previousValueRef.current;

    if (Math.abs(diff) > threshold) {
      // Use queueMicrotask to avoid synchronous setState in effect body
      queueMicrotask(() => {
        setChangeDirection(diff > 0 ? 'up' : 'down');
        setIsAnimating(true);
      });

      const timeout = setTimeout(() => {
        setIsAnimating(false);
        setChangeDirection(null);
      }, 1500);

      previousValueRef.current = value;
      return () => clearTimeout(timeout);
    }

    previousValueRef.current = value;
  }, [value, threshold]);

  return { changeDirection, isAnimating };
}

/**
 * Animated value display with change indicator
 */
interface AnimatedValueProps {
  value: number;
  format: (v: number) => string;
  baseClassName: string;
  animated?: boolean;
  threshold?: number;
}

function AnimatedValue({ value, format, baseClassName, animated = true, threshold = 0.01 }: AnimatedValueProps) {
  const { changeDirection, isAnimating } = useValueChange(value, threshold);

  const animationClass = isAnimating
    ? changeDirection === 'up'
      ? 'animate-pulse bg-green-100 dark:bg-green-900/30 rounded px-1 -mx-1'
      : 'animate-pulse bg-red-100 dark:bg-red-900/30 rounded px-1 -mx-1'
    : '';

  return (
    <span className={`${baseClassName} ${animated ? animationClass : ''} transition-all duration-300`}>
      {format(value)}
      {animated && isAnimating && changeDirection && (
        <span
          className={`ml-1 text-sm ${
            changeDirection === 'up' ? 'text-green-500' : 'text-red-500'
          }`}
        >
          {changeDirection === 'up' ? '↑' : '↓'}
        </span>
      )}
    </span>
  );
}

/**
 * MetricsSummary Component
 *
 * Displays a summary of key metrics for the observability dashboard.
 * Supports animated value changes when receiving real-time updates.
 */
export function MetricsSummary({
  totalRequests,
  successRate,
  avgDuration,
  errorCount,
  animated = false,
}: MetricsSummaryProps) {
  const getSuccessRateColor = () => {
    if (successRate >= 99) return 'text-green-600 dark:text-green-400';
    if (successRate >= 95) return 'text-yellow-600 dark:text-yellow-400';
    return 'text-red-600 dark:text-red-400';
  };

  const getDurationColor = () => {
    if (avgDuration <= 100) return 'text-green-600 dark:text-green-400';
    if (avgDuration <= 500) return 'text-yellow-600 dark:text-yellow-400';
    return 'text-red-600 dark:text-red-400';
  };

  return (
    <div
      className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-8"
      data-testid="metrics-summary"
    >
      {/* Total Requests */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4">
        <div className="flex items-center justify-between">
          <div>
            <p className="text-sm font-medium text-gray-500 dark:text-gray-400">
              Total Requests
            </p>
            <div className="text-2xl font-bold text-gray-900 dark:text-white mt-1">
              <AnimatedValue
                value={totalRequests}
                format={(v) => v.toLocaleString()}
                baseClassName="text-2xl font-bold text-gray-900 dark:text-white"
                animated={animated}
                threshold={1}
              />
            </div>
          </div>
          <div className="p-3 bg-blue-100 dark:bg-blue-900/30 rounded-full">
            <svg
              className="w-6 h-6 text-blue-600 dark:text-blue-400"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M13 10V3L4 14h7v7l9-11h-7z"
              />
            </svg>
          </div>
        </div>
        <p className="text-xs text-gray-500 dark:text-gray-400 mt-2">Last hour</p>
      </div>

      {/* Success Rate */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4">
        <div className="flex items-center justify-between">
          <div>
            <p className="text-sm font-medium text-gray-500 dark:text-gray-400">
              Success Rate
            </p>
            <div className="mt-1">
              <AnimatedValue
                value={successRate}
                format={(v) => `${v.toFixed(2)}%`}
                baseClassName={`text-2xl font-bold ${getSuccessRateColor()}`}
                animated={animated}
                threshold={0.01}
              />
            </div>
          </div>
          <div className="p-3 bg-green-100 dark:bg-green-900/30 rounded-full">
            <svg
              className="w-6 h-6 text-green-600 dark:text-green-400"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
              />
            </svg>
          </div>
        </div>
        <p className="text-xs text-gray-500 dark:text-gray-400 mt-2">Last hour</p>
      </div>

      {/* Avg Response Time */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4">
        <div className="flex items-center justify-between">
          <div>
            <p className="text-sm font-medium text-gray-500 dark:text-gray-400">
              Avg Response
            </p>
            <div className="mt-1">
              <AnimatedValue
                value={avgDuration}
                format={(v) => `${v.toFixed(0)}ms`}
                baseClassName={`text-2xl font-bold ${getDurationColor()}`}
                animated={animated}
                threshold={5}
              />
            </div>
          </div>
          <div className="p-3 bg-purple-100 dark:bg-purple-900/30 rounded-full">
            <svg
              className="w-6 h-6 text-purple-600 dark:text-purple-400"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
              />
            </svg>
          </div>
        </div>
        <p className="text-xs text-gray-500 dark:text-gray-400 mt-2">Last hour</p>
      </div>

      {/* Error Count */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4">
        <div className="flex items-center justify-between">
          <div>
            <p className="text-sm font-medium text-gray-500 dark:text-gray-400">
              Errors
            </p>
            <div className="mt-1">
              <AnimatedValue
                value={errorCount}
                format={(v) => v.toString()}
                baseClassName={`text-2xl font-bold ${
                  errorCount > 0
                    ? 'text-red-600 dark:text-red-400'
                    : 'text-gray-900 dark:text-white'
                }`}
                animated={animated}
                threshold={1}
              />
            </div>
          </div>
          <div className="p-3 bg-red-100 dark:bg-red-900/30 rounded-full">
            <svg
              className="w-6 h-6 text-red-600 dark:text-red-400"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
              />
            </svg>
          </div>
        </div>
        <p className="text-xs text-gray-500 dark:text-gray-400 mt-2">Last 24 hours</p>
      </div>
    </div>
  );
}

export default MetricsSummary;