import React, { useState, useEffect } from 'react';
import MetricCard from './MetricCard';
import type { BesuMetrics, Environment } from '../../../types';

interface Props {
  environment?: string;
  onEnvironmentChange: (env: string) => void;
}

const BesuMonitoring: React.FC<Props> = ({ environment, onEnvironmentChange }) => {
  const [selectedEnvironment, setSelectedEnvironment] = useState(environment || '');
  const [environments, setEnvironments] = useState<Environment[]>([]);
  const [metrics, setMetrics] = useState<BesuMetrics | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    loadEnvironments();
    if (selectedEnvironment) {
      loadMetrics();
    }
  }, [selectedEnvironment]);

  const loadEnvironments = async () => {
    try {
      const response = await fetch('/api/environments');
      if (response.ok) {
        setEnvironments(await response.json());
      }
    } catch (error) {
      console.error('Failed to load environments:', error);
    }
  };

  const loadMetrics = async () => {
    if (!selectedEnvironment) return;
    
    setLoading(true);
    try {
      const response = await fetch(`/api/monitoring/besu?environment=${selectedEnvironment}`);
      if (response.ok) {
        setMetrics(await response.json());
      }
    } catch (error) {
      console.error('Failed to load Besu metrics:', error);
    } finally {
      setLoading(false);
    }
  };

  const collectMetrics = async () => {
    if (!selectedEnvironment) {
      alert('Please select an environment first');
      return;
    }
    
    setLoading(true);
    try {
      const response = await fetch(`/api/monitoring/environments/${selectedEnvironment}/collect`, {
        method: 'POST',
      });
      if (response.ok) {
        await loadMetrics();
      }
    } catch (error) {
      console.error('Failed to collect metrics:', error);
    } finally {
      setLoading(false);
    }
  };

  const capitalize = (str: string): string => {
    return str.charAt(0).toUpperCase() + str.slice(1);
  };

  return (
    <div className="besu-monitoring">
      <div className="flex justify-between items-center mb-6">
        <h2 className="text-2xl font-bold">Besu Monitoring</h2>
        <div className="flex gap-4">
          <select
            value={selectedEnvironment}
            onChange={(e) => {
              setSelectedEnvironment(e.target.value);
              onEnvironmentChange(e.target.value);
            }}
            className="px-4 py-2 border border-gray-300 rounded-lg"
          >
            <option value="">All Environments</option>
            {environments.map((env) => (
              <option key={env.name} value={env.name}>
                {env.name}
              </option>
            ))}
          </select>
          <button onClick={loadMetrics} className="btn btn-secondary">
            <i className="fas fa-sync-alt mr-2"></i>Refresh
          </button>
          <button onClick={collectMetrics} className="btn btn-primary" disabled={loading}>
            <i className="fas fa-download mr-2"></i>Collect Metrics
          </button>
        </div>
      </div>

      {loading ? (
        <div className="text-center py-8">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-500 mx-auto"></div>
          <p className="mt-4 text-gray-600">Loading metrics...</p>
        </div>
      ) : metrics ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          <MetricCard
            title="Block Number"
            value={metrics.blockNumber.toLocaleString()}
            unit="blocks"
            icon="fas fa-cube"
            status={metrics.syncStatus === 'synced' ? 'healthy' : 'degraded'}
          />
          <MetricCard
            title="Peer Count"
            value={metrics.peerCount.toString()}
            unit="peers"
            icon="fas fa-users"
            status={metrics.peerCount > 3 ? 'healthy' : 'degraded'}
          />
          <MetricCard
            title="Sync Status"
            value={capitalize(metrics.syncStatus)}
            icon="fas fa-sync"
            status={metrics.syncStatus === 'synced' ? 'healthy' : 'degraded'}
          />
          <MetricCard
            title="Gas Price"
            value={metrics.gasPrice}
            icon="fas fa-gas-pump"
            status="healthy"
          />
          <MetricCard
            title="Pending Transactions"
            value={metrics.pendingTransactions.toString()}
            unit="txns"
            icon="fas fa-clock"
            status={metrics.pendingTransactions < 50 ? 'healthy' : 'degraded'}
          />
          <MetricCard
            title="CPU Usage"
            value={metrics.cpuUsage.toFixed(1)}
            unit="%"
            icon="fas fa-microchip"
            status={metrics.cpuUsage < 80 ? 'healthy' : metrics.cpuUsage < 90 ? 'degraded' : 'unhealthy'}
          />
          <MetricCard
            title="Memory Usage"
            value={metrics.memoryUsage.toFixed(1)}
            unit="%"
            icon="fas fa-memory"
            status={metrics.memoryUsage < 85 ? 'healthy' : metrics.memoryUsage < 95 ? 'degraded' : 'unhealthy'}
          />
          <MetricCard
            title="Disk Usage"
            value={metrics.diskUsage.toFixed(1)}
            unit="%"
            icon="fas fa-hdd"
            status={metrics.diskUsage < 80 ? 'healthy' : metrics.diskUsage < 90 ? 'degraded' : 'unhealthy'}
          />
          <MetricCard
            title="Chain ID"
            value={metrics.chainId.toString()}
            icon="fas fa-link"
            status="healthy"
          />
        </div>
      ) : (
        <div className="text-center py-8 text-gray-500">
          No metrics available. Click "Collect Metrics" to gather data.
        </div>
      )}
    </div>
  );
};

export default BesuMonitoring;

