// Service Monitoring Page
// Service health and metrics display

import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import { apiClient } from '@/services/api/client';

interface ServiceMetrics {
  serviceName: string;
  status: string;
  uptime: number;
  latency: number;
  errorRate: number;
  throughput: number;
  lastUpdated: Date;
}

interface ServiceHealth {
  overall: string;
  services: ServiceMetrics[];
  timestamp: Date;
}

export const ServiceMonitoring: React.FC = () => {
  const { subscriptionId } = useParams<{ subscriptionId?: string }>();
  const [health, setHealth] = useState<ServiceHealth | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchHealth = async () => {
      if (!subscriptionId) {
        setError('Subscription ID required');
        setLoading(false);
        return;
      }

      try {
        setLoading(true);
        const data = await apiClient.get<{ success: boolean; data: ServiceHealth }>(
          `/api/v1/iru/portal/monitoring/${subscriptionId}/health`
        );
        if (data.success) {
          setHealth(data.data);
        }
      } catch (err: any) {
        setError(err.message || 'Failed to load service health');
      } finally {
        setLoading(false);
      }
    };

    fetchHealth();
    const interval = setInterval(fetchHealth, 30000); // Refresh every 30 seconds
    return () => clearInterval(interval);
  }, [subscriptionId]);

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">Loading service health...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="text-red-600 text-xl mb-4">Error</div>
          <p className="text-gray-600">{error}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="container mx-auto px-4">
        <h1 className="text-3xl font-bold mb-8 text-gray-800">Service Monitoring</h1>

        {health && (
          <div className="space-y-6">
            {/* Overall Status */}
            <div className="bg-white rounded-lg shadow p-6">
              <h2 className="text-2xl font-semibold mb-4 text-gray-800">Overall Status</h2>
              <div className="flex items-center gap-4">
                <span className={`text-4xl font-bold ${
                  health.overall === 'healthy' ? 'text-green-600' : 'text-red-600'
                }`}>
                  {health.overall === 'healthy' ? '✓' : '✗'}
                </span>
                <div>
                  <div className="text-lg font-semibold text-gray-800 capitalize">
                    {health.overall}
                  </div>
                  <div className="text-sm text-gray-500">
                    Last updated: {new Date(health.timestamp).toLocaleString()}
                  </div>
                </div>
              </div>
            </div>

            {/* Services */}
            <div className="bg-white rounded-lg shadow p-6">
              <h2 className="text-2xl font-semibold mb-4 text-gray-800">Services</h2>
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="border-b">
                      <th className="text-left py-3 px-4 font-semibold text-gray-700">Service</th>
                      <th className="text-left py-3 px-4 font-semibold text-gray-700">Status</th>
                      <th className="text-right py-3 px-4 font-semibold text-gray-700">Uptime</th>
                      <th className="text-right py-3 px-4 font-semibold text-gray-700">Latency</th>
                      <th className="text-right py-3 px-4 font-semibold text-gray-700">Error Rate</th>
                      <th className="text-right py-3 px-4 font-semibold text-gray-700">Throughput</th>
                    </tr>
                  </thead>
                  <tbody>
                    {health.services.map((service, index) => (
                      <tr key={index} className="border-b hover:bg-gray-50">
                        <td className="py-3 px-4 font-medium text-gray-800">{service.serviceName}</td>
                        <td className="py-3 px-4">
                          <span className={`px-2 py-1 rounded text-sm font-semibold ${
                            service.status === 'healthy'
                              ? 'bg-green-100 text-green-800'
                              : 'bg-red-100 text-red-800'
                          }`}>
                            {service.status}
                          </span>
                        </td>
                        <td className="py-3 px-4 text-right text-gray-700">{service.uptime.toFixed(2)}%</td>
                        <td className="py-3 px-4 text-right text-gray-700">{service.latency}ms</td>
                        <td className="py-3 px-4 text-right text-gray-700">{(service.errorRate * 100).toFixed(2)}%</td>
                        <td className="py-3 px-4 text-right text-gray-700">{service.throughput}/s</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default ServiceMonitoring;
