'use client';

import { useEffect, useState } from 'react';
import type { ConnectionStatus } from '@/lib/signalr/types';

interface ConnectionStatusIndicatorProps {
  connectionState: ConnectionStatus;
  className?: string;
}

export function ConnectionStatusIndicator({
  connectionState,
  className = '',
}: ConnectionStatusIndicatorProps) {
  const [visible, setVisible] = useState(false);

  // Only show indicator when not connected
  useEffect(() => {
    if (connectionState !== 'connected') {
      setVisible(true);
    } else {
      // Hide after a brief delay when connected
      const timer = setTimeout(() => setVisible(false), 2000);
      return () => clearTimeout(timer);
    }
  }, [connectionState]);

  if (!visible && connectionState === 'connected') {
    return null;
  }

  const getStatusConfig = () => {
    switch (connectionState) {
      case 'connected':
        return {
          color: 'bg-green-500',
          text: 'Online',
          pulse: false,
        };
      case 'connecting':
        return {
          color: 'bg-yellow-500',
          text: 'Connecting...',
          pulse: true,
        };
      case 'reconnecting':
        return {
          color: 'bg-orange-500',
          text: 'Reconnecting...',
          pulse: true,
        };
      case 'disconnected':
        return {
          color: 'bg-gray-500',
          text: 'Offline',
          pulse: false,
        };
      case 'failed':
        return {
          color: 'bg-red-500',
          text: 'Connection Failed',
          pulse: false,
        };
      default:
        return {
          color: 'bg-gray-500',
          text: 'Unknown',
          pulse: false,
        };
    }
  };

  const { color, text, pulse } = getStatusConfig();

  return (
    <div
      className={`fixed bottom-4 right-4 z-50 flex items-center gap-2 rounded-lg border border-gray-200 bg-white px-4 py-2 shadow-lg dark:border-gray-700 dark:bg-gray-800 ${className}`}
    >
      <span
        className={`h-3 w-3 rounded-full ${color} ${pulse ? 'animate-pulse' : ''}`}
      ></span>
      <span className="text-sm font-medium text-gray-700 dark:text-gray-300">
        {text}
      </span>
    </div>
  );
}
