/**
 * Performance Indicator Component
 * 
 * Visual performance indicator based on response time and throughput
 * Pure server performance metrics, without cache
 */

import React from 'react';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';

interface PerformanceIndicatorProps {
  responseTime: number; // ms
  throughput: number; // k/s
}

type PerformanceLevel = 'poor' | 'fair' | 'good' | 'excellent';

interface PerformanceData {
  level: PerformanceLevel;
  score: number; // 0-100
  label: string;
  color: string;
  bgColor: string;
  borderColor: string;
  textColor: string;
}

function calculateResponseTimeScore(responseTime: number): number {
  // 0.6ms = kiváló kezdet, 10%-os lépcsők
  if (responseTime <= 0.0006) return 100; // < 0.6ms
  if (responseTime <= 0.001) return 90;   // 0.6-1ms
  if (responseTime <= 0.002) return 80;   // 1-2ms
  if (responseTime <= 0.003) return 70;   // 2-3ms
  if (responseTime <= 0.005) return 60;   // 3-5ms
  if (responseTime <= 0.007) return 50;   // 5-7ms
  if (responseTime <= 0.01) return 40;    // 7-10ms
  if (responseTime <= 0.02) return 30;    // 10-20ms
  if (responseTime <= 0.05) return 20;    // 20-50ms
  if (responseTime <= 0.1) return 10;     // 50-100ms
  return 0;                               // > 100ms
}

function calculateThroughputScore(throughput: number): number {
  // 6000 k/s = kiváló, 10%-os lépcsők
  if (throughput >= 6000) return 100;   // >= 6000 k/s
  if (throughput >= 5000) return 90;    // 5000-6000 k/s
  if (throughput >= 4000) return 80;    // 4000-5000 k/s
  if (throughput >= 3000) return 70;    // 3000-4000 k/s
  if (throughput >= 2000) return 60;    // 2000-3000 k/s
  if (throughput >= 1500) return 50;    // 1500-2000 k/s
  if (throughput >= 1000) return 40;    // 1000-1500 k/s
  if (throughput >= 500) return 30;     // 500-1000 k/s
  if (throughput >= 250) return 20;     // 250-500 k/s
  if (throughput >= 100) return 10;     // 100-250 k/s
  return 0;                             // < 100 k/s
}

function getPerformanceLevel(score: number): PerformanceLevel {
  if (score >= 85) return 'excellent';
  if (score >= 70) return 'good';
  if (score >= 50) return 'fair';
  return 'poor';
}

function getPerformanceData(level: PerformanceLevel, score: number, t: (key: string) => string): PerformanceData {
  switch (level) {
    case 'excellent':
      return {
        level,
        score,
        label: t('performance.level_excellent'),
        color: '#10b981', // emerald-500
        bgColor: '#d1fae5', // emerald-100
        borderColor: '#34d399', // emerald-400
        textColor: '#065f46', // emerald-900
      };
    case 'good':
      return {
        level,
        score,
        label: t('performance.level_good'),
        color: '#3b82f6', // blue-500
        bgColor: '#dbeafe', // blue-100
        borderColor: '#60a5fa', // blue-400
        textColor: '#1e3a8a', // blue-900
      };
    case 'fair':
      return {
        level,
        score,
        label: t('performance.level_fair'),
        color: '#f59e0b', // amber-500
        bgColor: '#fef3c7', // amber-100
        borderColor: '#fbbf24', // amber-400
        textColor: '#78350f', // amber-900
      };
    case 'poor':
      return {
        level,
        score,
        label: t('performance.level_poor'),
        color: '#ef4444', // red-500
        bgColor: '#fee2e2', // red-100
        borderColor: '#f87171', // red-400
        textColor: '#7f1d1d', // red-900
      };
  }
}

export default function PerformanceIndicator({
  responseTime,
  throughput,
}: PerformanceIndicatorProps) {
  const { t } = useTranslation();
  
  const performanceData = useMemo(() => {
    // Convert ms to seconds for response time
    const responseTimeInSeconds = responseTime / 1000;
    
    // Calculate scores
    const responseScore = calculateResponseTimeScore(responseTimeInSeconds);
    const throughputScore = calculateThroughputScore(throughput);
    
    // Weighted final score (ONLY response time + throughput, NO cache bonus)
    const finalScore = Math.min(
      100,
      Math.max(0, responseScore * 0.5 + throughputScore * 0.5)
    );
    
    const level = getPerformanceLevel(finalScore);
    
    return getPerformanceData(level, Math.round(finalScore), t);
  }, [responseTime, throughput, t]);

  // Progress bar segment positions (0-100 scale)
  const segments = [
    { end: 50, label: t('performance.level_poor'), color: '#ef4444' },
    { end: 70, label: t('performance.level_fair'), color: '#f59e0b' },
    { end: 85, label: t('performance.level_good'), color: '#3b82f6' },
    { end: 100, label: t('performance.level_excellent'), color: '#10b981' },
  ];

  return (
    <div className="bg-white rounded-lg border border-gray-200 p-4 shadow-sm">
      <div className="flex items-center justify-between mb-3">
        <h3 className="text-sm font-semibold text-gray-700">{t('performance.server_performance')}</h3>
        <div 
          className="px-3 py-1 rounded-full text-xs font-bold border-2"
          style={{
            backgroundColor: performanceData.bgColor,
            borderColor: performanceData.borderColor,
            color: performanceData.textColor,
          }}
        >
          {performanceData.label}
        </div>
      </div>

      {/* Progress Bar Container */}
      <div className="relative h-8 bg-gray-100 rounded-lg overflow-hidden border border-gray-200">
        {/* Szegmensek háttere */}
        <div className="absolute inset-0 flex">
          {segments.map((segment, idx) => {
            const start = idx === 0 ? 0 : segments[idx - 1].end;
            const width = segment.end - start;
            return (
              <div
                key={idx}
                className="relative border-r border-gray-300 last:border-r-0"
                style={{
                  width: `${width}%`,
                  backgroundColor: `${segment.color}15`, // 15 = ~10% opacity
                }}
              >
                {/* Szegmens címke */}
                <div className="absolute bottom-full mb-1 left-1/2 transform -translate-x-1/2 text-xs text-gray-500 whitespace-nowrap">
                  {segment.label}
                </div>
              </div>
            );
          })}
        </div>

        {/* Animated Progress Fill */}
        <div
          className="absolute inset-y-0 left-0 transition-all duration-700 ease-out rounded-lg"
          style={{
            width: `${performanceData.score}%`,
            backgroundColor: performanceData.color,
            boxShadow: `0 0 10px ${performanceData.color}40`,
          }}
        >
          {/* Shine effect */}
          <div className="absolute inset-0 bg-gradient-to-r from-transparent via-white to-transparent opacity-30 animate-pulse" />
        </div>

        {/* Score Indicator */}
        <div
          className="absolute top-1/2 transform -translate-y-1/2 transition-all duration-700 ease-out"
          style={{ left: `${performanceData.score}%` }}
        >
          <div
            className="relative w-6 h-6 rounded-full border-3 shadow-lg transform -translate-x-1/2"
            style={{
              backgroundColor: 'white',
              borderColor: performanceData.color,
              borderWidth: '3px',
            }}
          >
            {/* Pulsing ring */}
            <div
              className="absolute inset-0 rounded-full animate-ping opacity-75"
              style={{ backgroundColor: performanceData.color }}
            />
          </div>
          
          {/* Score Label */}
          <div
            className="absolute top-full mt-2 left-1/2 transform -translate-x-1/2 px-2 py-1 rounded text-xs font-bold whitespace-nowrap shadow-sm"
            style={{
              backgroundColor: performanceData.color,
              color: 'white',
            }}
          >
            {performanceData.score}
          </div>
        </div>
      </div>

      {/* Detailed Breakdown */}
      <div className="mt-4 grid grid-cols-2 gap-2 text-xs">
        <div className="text-center">
          <div className="text-gray-500 mb-1">{t('performance.response_time')}</div>
          <div className="font-semibold text-gray-800">
            {calculateResponseTimeScore(responseTime / 1000).toFixed(0)}/100
          </div>
        </div>
        <div className="text-center border-l border-gray-200">
          <div className="text-gray-500 mb-1">{t('performance.throughput')}</div>
          <div className="font-semibold text-gray-800">
            {calculateThroughputScore(throughput).toFixed(0)}/100
          </div>
        </div>
      </div>

      {/* Performance Tips */}
      {performanceData.level === 'poor' && (
        <div className="mt-3 p-2 bg-red-50 border border-red-200 rounded text-xs text-red-800">
          <strong>⚠️ {t('performance.warning')}:</strong> {t('performance.warning_poor')}
        </div>
      )}
      {performanceData.level === 'fair' && (
        <div className="mt-3 p-2 bg-amber-50 border border-amber-200 rounded text-xs text-amber-800">
          <strong>💡 {t('performance.tip')}:</strong> {t('performance.tip_fair')}
        </div>
      )}
    </div>
  );
}
