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

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

const ChainlinkCCIPMonitoring: React.FC<Props> = ({ environment, onEnvironmentChange }) => {
  const [selectedEnvironment, setSelectedEnvironment] = useState(environment || '');
  const [environments, setEnvironments] = useState<Environment[]>([]);
  const [metrics, setMetrics] = useState<ChainlinkCCIPMetrics | 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/chainlink-ccip?environment=${selectedEnvironment}`);
      if (response.ok) {
        setMetrics(await response.json());
      }
    } catch (error) {
      console.error('Failed to load Chainlink CCIP 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);
    }
  };

  return (
    <div className="chainlink-ccip-monitoring">
      <div className="flex justify-between items-center mb-6">
        <h2 className="text-2xl font-bold">Chainlink CCIP 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>
        </div>
      ) : metrics ? (
        <div className="space-y-6">
          <div className="card">
            <h3 className="text-lg font-semibold mb-4">Router Information</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <div className="text-sm text-gray-500">Router Address</div>
                <div className="font-mono text-sm">{metrics.routerAddress}</div>
              </div>
              <div>
                <div className="text-sm text-gray-500">Fee Token Balance</div>
                <div className="text-lg font-semibold">{metrics.feeTokenBalance}</div>
              </div>
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <MetricCard title="Active Chains" value={metrics.activeChains.toString()} unit="chains" icon="fas fa-link" status="healthy" />
            <MetricCard title="Total Messages" value={metrics.totalMessages.toLocaleString()} unit="messages" icon="fas fa-envelope" status="healthy" />
            <MetricCard title="Pending Messages" value={metrics.pendingMessages.toString()} unit="messages" icon="fas fa-clock" status={metrics.pendingMessages < 50 ? 'healthy' : 'degraded'} />
            <MetricCard title="Failed Messages" value={metrics.failedMessages.toString()} unit="messages" icon="fas fa-exclamation-triangle" status={metrics.failedMessages < 10 ? 'healthy' : metrics.failedMessages < 20 ? 'degraded' : 'unhealthy'} />
            <MetricCard title="Average Latency" value={metrics.averageLatency.toFixed(2)} unit="ms" icon="fas fa-tachometer-alt" status={metrics.averageLatency < 500 ? 'healthy' : metrics.averageLatency < 1000 ? 'degraded' : 'unhealthy'} />
            <MetricCard title="Token Transfers" value={metrics.tokenTransfers.toLocaleString()} unit="transfers" icon="fas fa-coins" status="healthy" />
            <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'} />
          </div>
        </div>
      ) : (
        <div className="text-center py-8 text-gray-500">
          No metrics available. Click "Collect Metrics" to gather data.
        </div>
      )}
    </div>
  );
};

export default ChainlinkCCIPMonitoring;

