import React, { useState, useEffect } from 'react';
import { io, Socket } from 'socket.io-client';
import ServiceHealthCard from '../components/monitoring/ServiceHealthCard';
import BesuMonitoring from '../components/monitoring/BesuMonitoring';
import CactiMonitoring from '../components/monitoring/CactiMonitoring';
import FireflyMonitoring from '../components/monitoring/FireflyMonitoring';
import ChainlinkCCIPMonitoring from '../components/monitoring/ChainlinkCCIPMonitoring';
import type { ServiceHealthSummary, ServiceType } from '../../types';

const MonitoringDashboard: React.FC = () => {
  const [selectedService, setSelectedService] = useState<ServiceType | null>('besu');
  const [selectedEnvironment, setSelectedEnvironment] = useState<string>('');
  const [healthData, setHealthData] = useState<Record<string, ServiceHealthSummary>>({});
  const [socket, setSocket] = useState<Socket | null>(null);

  const serviceTypes = [
    { type: 'besu' as ServiceType, name: 'Besu', icon: 'fas fa-cube' },
    { type: 'cacti' as ServiceType, name: 'Cacti', icon: 'fas fa-link' },
    { type: 'firefly' as ServiceType, name: 'Firefly', icon: 'fas fa-fire' },
    { type: 'chainlink-ccip' as ServiceType, name: 'Chainlink CCIP', icon: 'fas fa-project-diagram' },
  ];

  const loadHealthData = async () => {
    try {
      const response = await fetch('/api/monitoring/dashboard');
      if (response.ok) {
        const data = await response.json();
        setHealthData({
          besu: data.besu,
          cacti: data.cacti,
          firefly: data.firefly,
          chainlinkCcip: data.chainlinkCcip,
        });
      }
    } catch (error) {
      console.error('Failed to load health data:', error);
    }
  };

  useEffect(() => {
    loadHealthData();
    
    // Initialize WebSocket for real-time updates
    const ws = io(window.location.origin);
    ws.on('connect', () => {
      console.log('Connected to monitoring WebSocket');
    });
    
    ws.on('admin-update', (data: { type: string; data: any }) => {
      if (data.type === 'monitoring-updated') {
        loadHealthData();
      }
    });
    
    setSocket(ws);
    
    // Auto-refresh every 30 seconds
    const interval = setInterval(loadHealthData, 30000);
    
    return () => {
      clearInterval(interval);
      ws.disconnect();
    };
  }, []);

  return (
    <div className="monitoring-dashboard">
      <div className="mb-8">
        <h1 className="text-3xl font-bold mb-2">Service Monitoring</h1>
        <p className="text-gray-600">Monitor Besu, Cacti, Firefly, and Chainlink CCIP services</p>
      </div>

      {/* Service Health Overview */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        {serviceTypes.map((service) => (
          <ServiceHealthCard
            key={service.type}
            serviceType={service.type}
            health={healthData[service.type]}
            onClick={() => setSelectedService(service.type)}
          />
        ))}
      </div>

      {/* Service Tabs */}
      <div className="border-b border-gray-200 mb-6">
        <nav className="flex space-x-8">
          {serviceTypes.map((service) => (
            <button
              key={service.type}
              onClick={() => setSelectedService(service.type)}
              className={`py-4 px-1 border-b-2 font-medium text-sm ${
                selectedService === service.type
                  ? 'border-primary-500 text-primary-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              }`}
            >
              <i className={`${service.icon} mr-2`}></i>
              {service.name}
            </button>
          ))}
        </nav>
      </div>

      {/* Service Details */}
      {selectedService && (
        <div className="space-y-6">
          {selectedService === 'besu' && (
            <BesuMonitoring
              environment={selectedEnvironment}
              onEnvironmentChange={setSelectedEnvironment}
            />
          )}
          {selectedService === 'cacti' && (
            <CactiMonitoring
              environment={selectedEnvironment}
              onEnvironmentChange={setSelectedEnvironment}
            />
          )}
          {selectedService === 'firefly' && (
            <FireflyMonitoring
              environment={selectedEnvironment}
              onEnvironmentChange={setSelectedEnvironment}
            />
          )}
          {selectedService === 'chainlink-ccip' && (
            <ChainlinkCCIPMonitoring
              environment={selectedEnvironment}
              onEnvironmentChange={setSelectedEnvironment}
            />
          )}
        </div>
      )}
    </div>
  );
};

export default MonitoringDashboard;

