/**
 * ConnectionStatus Component
 * Displays WebSocket/API connection status indicator
 * OQI-007: LLM Strategy Agent
 */

import React, { useMemo } from 'react';
import {
  Wifi,
  WifiOff,
  Signal,
  SignalLow,
  SignalMedium,
  SignalHigh,
  RefreshCw,
  AlertCircle,
  CheckCircle,
  Clock,
  Zap,
} from 'lucide-react';

export type ConnectionState =
  | 'connected'
  | 'connecting'
  | 'disconnected'
  | 'reconnecting'
  | 'error'
  | 'degraded';

export interface ConnectionMetrics {
  latency?: number; // ms
  lastPing?: string; // ISO timestamp
  reconnectAttempts?: number;
  maxReconnectAttempts?: number;
  uptime?: number; // seconds
  messagesReceived?: number;
  messagesSent?: number;
}

export interface ConnectionStatusProps {
  state: ConnectionState;
  metrics?: ConnectionMetrics;
  onReconnect?: () => void;
  variant?: 'badge' | 'indicator' | 'detailed';
  showMetrics?: boolean;
  className?: string;
}

const ConnectionStatus: React.FC<ConnectionStatusProps> = ({
  state,
  metrics,
  onReconnect,
  variant = 'badge',
  showMetrics = false,
  className = '',
}) => {
  const config = useMemo(() => {
    switch (state) {
      case 'connected':
        return {
          icon: <Wifi className="w-4 h-4" />,
          label: 'Connected',
          color: 'text-green-400',
          bgColor: 'bg-green-500/20',
          borderColor: 'border-green-500/30',
          pulseColor: 'bg-green-400',
        };
      case 'connecting':
        return {
          icon: <RefreshCw className="w-4 h-4 animate-spin" />,
          label: 'Connecting...',
          color: 'text-blue-400',
          bgColor: 'bg-blue-500/20',
          borderColor: 'border-blue-500/30',
          pulseColor: 'bg-blue-400',
        };
      case 'disconnected':
        return {
          icon: <WifiOff className="w-4 h-4" />,
          label: 'Disconnected',
          color: 'text-gray-400',
          bgColor: 'bg-gray-500/20',
          borderColor: 'border-gray-500/30',
          pulseColor: 'bg-gray-400',
        };
      case 'reconnecting':
        return {
          icon: <RefreshCw className="w-4 h-4 animate-spin" />,
          label: 'Reconnecting...',
          color: 'text-yellow-400',
          bgColor: 'bg-yellow-500/20',
          borderColor: 'border-yellow-500/30',
          pulseColor: 'bg-yellow-400',
        };
      case 'error':
        return {
          icon: <AlertCircle className="w-4 h-4" />,
          label: 'Connection Error',
          color: 'text-red-400',
          bgColor: 'bg-red-500/20',
          borderColor: 'border-red-500/30',
          pulseColor: 'bg-red-400',
        };
      case 'degraded':
        return {
          icon: <SignalLow className="w-4 h-4" />,
          label: 'Degraded',
          color: 'text-orange-400',
          bgColor: 'bg-orange-500/20',
          borderColor: 'border-orange-500/30',
          pulseColor: 'bg-orange-400',
        };
      default:
        return {
          icon: <Signal className="w-4 h-4" />,
          label: 'Unknown',
          color: 'text-gray-400',
          bgColor: 'bg-gray-500/20',
          borderColor: 'border-gray-500/30',
          pulseColor: 'bg-gray-400',
        };
    }
  }, [state]);

  const getLatencyIndicator = (latency?: number) => {
    if (!latency) return { icon: <Signal className="w-3 h-3" />, label: 'N/A', color: 'text-gray-400' };
    if (latency < 100) return { icon: <SignalHigh className="w-3 h-3" />, label: 'Excellent', color: 'text-green-400' };
    if (latency < 300) return { icon: <SignalMedium className="w-3 h-3" />, label: 'Good', color: 'text-yellow-400' };
    return { icon: <SignalLow className="w-3 h-3" />, label: 'Poor', color: 'text-red-400' };
  };

  const formatUptime = (seconds?: number) => {
    if (!seconds) return 'N/A';
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;
    if (hours > 0) return `${hours}h ${minutes}m`;
    if (minutes > 0) return `${minutes}m ${secs}s`;
    return `${secs}s`;
  };

  // Simple indicator variant (just a dot)
  if (variant === 'indicator') {
    return (
      <div className={`relative ${className}`} title={config.label}>
        <div className={`w-2.5 h-2.5 rounded-full ${config.pulseColor}`} />
        {(state === 'connected' || state === 'connecting') && (
          <div className={`absolute inset-0 w-2.5 h-2.5 rounded-full ${config.pulseColor} animate-ping opacity-75`} />
        )}
      </div>
    );
  }

  // Badge variant (icon + label)
  if (variant === 'badge') {
    return (
      <div
        className={`inline-flex items-center gap-2 px-3 py-1.5 rounded-full ${config.bgColor} border ${config.borderColor} ${className}`}
      >
        <span className={config.color}>{config.icon}</span>
        <span className={`text-sm font-medium ${config.color}`}>{config.label}</span>
        {(state === 'disconnected' || state === 'error') && onReconnect && (
          <button
            onClick={onReconnect}
            className="ml-1 p-0.5 hover:bg-white/10 rounded transition-colors"
            title="Reconnect"
          >
            <RefreshCw className="w-3.5 h-3.5" />
          </button>
        )}
      </div>
    );
  }

  // Detailed variant (full panel with metrics)
  const latencyInfo = getLatencyIndicator(metrics?.latency);

  return (
    <div className={`p-4 rounded-xl ${config.bgColor} border ${config.borderColor} ${className}`}>
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <div className={`p-2 rounded-lg ${config.bgColor}`}>
            <span className={config.color}>{config.icon}</span>
          </div>
          <div>
            <h4 className={`font-semibold ${config.color}`}>{config.label}</h4>
            {metrics?.lastPing && (
              <p className="text-xs text-gray-500">
                Last ping: {new Date(metrics.lastPing).toLocaleTimeString()}
              </p>
            )}
          </div>
        </div>

        {(state === 'disconnected' || state === 'error') && onReconnect && (
          <button
            onClick={onReconnect}
            className="flex items-center gap-2 px-3 py-1.5 bg-blue-500 text-white text-sm rounded-lg hover:bg-blue-600 transition-colors"
          >
            <RefreshCw className="w-4 h-4" />
            Reconnect
          </button>
        )}
      </div>

      {/* Metrics Grid */}
      {showMetrics && metrics && (
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
          {/* Latency */}
          <div className="p-3 bg-gray-800/50 rounded-lg">
            <div className="flex items-center gap-2 mb-1">
              <Zap className={`w-4 h-4 ${latencyInfo.color}`} />
              <span className="text-xs text-gray-400">Latency</span>
            </div>
            <div className="flex items-baseline gap-1">
              <span className="text-lg font-bold text-white">
                {metrics.latency ?? '--'}
              </span>
              <span className="text-xs text-gray-500">ms</span>
            </div>
          </div>

          {/* Uptime */}
          <div className="p-3 bg-gray-800/50 rounded-lg">
            <div className="flex items-center gap-2 mb-1">
              <Clock className="w-4 h-4 text-blue-400" />
              <span className="text-xs text-gray-400">Uptime</span>
            </div>
            <div className="text-lg font-bold text-white">
              {formatUptime(metrics.uptime)}
            </div>
          </div>

          {/* Messages Received */}
          <div className="p-3 bg-gray-800/50 rounded-lg">
            <div className="flex items-center gap-2 mb-1">
              <CheckCircle className="w-4 h-4 text-green-400" />
              <span className="text-xs text-gray-400">Received</span>
            </div>
            <div className="text-lg font-bold text-white">
              {metrics.messagesReceived ?? 0}
            </div>
          </div>

          {/* Messages Sent */}
          <div className="p-3 bg-gray-800/50 rounded-lg">
            <div className="flex items-center gap-2 mb-1">
              <Signal className="w-4 h-4 text-purple-400" />
              <span className="text-xs text-gray-400">Sent</span>
            </div>
            <div className="text-lg font-bold text-white">
              {metrics.messagesSent ?? 0}
            </div>
          </div>
        </div>
      )}

      {/* Reconnection Progress */}
      {state === 'reconnecting' && metrics?.reconnectAttempts !== undefined && (
        <div className="mt-4">
          <div className="flex items-center justify-between text-sm mb-2">
            <span className="text-gray-400">Reconnection attempt</span>
            <span className="text-yellow-400">
              {metrics.reconnectAttempts} / {metrics.maxReconnectAttempts || 5}
            </span>
          </div>
          <div className="h-1.5 bg-gray-700 rounded-full overflow-hidden">
            <div
              className="h-full bg-yellow-500 transition-all"
              style={{
                width: `${((metrics.reconnectAttempts || 0) / (metrics.maxReconnectAttempts || 5)) * 100}%`,
              }}
            />
          </div>
        </div>
      )}
    </div>
  );
};

export default ConnectionStatus;
