/**
 * Carrier Monitoring Dashboard
 */

import React, { useState, useEffect } from 'react';
import { CarrierStats, CarrierHealthCheck } from '@/types/carrier';

export const CarrierMonitoring: React.FC = () => {
  const [stats, setStats] = useState<CarrierStats[]>([]);
  const [health, setHealth] = useState<CarrierHealthCheck[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [timeRange, setTimeRange] = useState('24h');

  useEffect(() => {
    fetchMonitoringData();
    // Refresh every 30 seconds
    const interval = setInterval(fetchMonitoringData, 30000);
    return () => clearInterval(interval);
  }, [timeRange]);

  const fetchMonitoringData = async () => {
    setLoading(true);
    setError(null);

    try {
      const [statsRes, healthRes] = await Promise.all([
        fetch(`/api/v1/carriers/stats?timeRange=${timeRange}`, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('accessToken')}`,
          },
        }),
        fetch('/api/v1/carriers/health', {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('accessToken')}`,
          },
        }),
      ]);

      if (!statsRes.ok || !healthRes.ok) {
        throw new Error('Failed to fetch monitoring data');
      }

      const [statsData, healthData] = await Promise.all([statsRes.json(), healthRes.json()]);

      setStats(statsData);
      setHealth(healthData);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const getHealthStatus = (carrierId: string): CarrierHealthCheck | undefined => {
    return health.find(h => h.carrierId === carrierId);
  };

  const getHealthColor = (status: string) => {
    switch (status) {
      case 'healthy':
        return 'bg-green-100 text-green-800';
      case 'degraded':
        return 'bg-yellow-100 text-yellow-800';
      case 'down':
        return 'bg-red-100 text-red-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  // Calculate overall stats
  const totalRequests = stats.reduce((sum, s) => sum + s.totalRequests, 0);
  const totalSuccessful = stats.reduce((sum, s) => sum + s.successfulRequests, 0);
  const totalFailed = stats.reduce((sum, s) => sum + s.failedRequests, 0);
  const overallSuccessRate = totalRequests > 0 ? (totalSuccessful / totalRequests) * 100 : 0;
  const avgResponseTime =
    stats.length > 0 ? stats.reduce((sum, s) => sum + s.averageResponseTime, 0) / stats.length : 0;

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Header */}
        <div className="mb-8 flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">Carrier Monitoring</h1>
            <p className="mt-2 text-sm text-gray-600">
              Real-time monitoring of carrier API performance and health
            </p>
          </div>
          <div className="flex gap-2">
            <select
              value={timeRange}
              onChange={e => setTimeRange(e.target.value)}
              className="px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="1h">Last Hour</option>
              <option value="24h">Last 24 Hours</option>
              <option value="7d">Last 7 Days</option>
              <option value="30d">Last 30 Days</option>
            </select>
            <button
              onClick={fetchMonitoringData}
              disabled={loading}
              className="px-4 py-2 bg-blue-600 text-white rounded-md text-sm font-medium hover:bg-blue-700 disabled:opacity-50"
            >
              {loading ? 'Refreshing...' : 'Refresh'}
            </button>
          </div>
        </div>

        {/* Error */}
        {error && (
          <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-6">
            <p className="text-sm text-red-800">{error}</p>
          </div>
        )}

        {/* Overall Stats */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <div className="text-sm font-medium text-gray-500 mb-1">Total Requests</div>
            <div className="text-3xl font-bold text-gray-900">{totalRequests.toLocaleString()}</div>
          </div>

          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <div className="text-sm font-medium text-gray-500 mb-1">Success Rate</div>
            <div className="text-3xl font-bold text-green-600">
              {overallSuccessRate.toFixed(1)}%
            </div>
          </div>

          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <div className="text-sm font-medium text-gray-500 mb-1">Failed Requests</div>
            <div className="text-3xl font-bold text-red-600">{totalFailed.toLocaleString()}</div>
          </div>

          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <div className="text-sm font-medium text-gray-500 mb-1">Avg Response Time</div>
            <div className="text-3xl font-bold text-blue-600">{avgResponseTime.toFixed(0)}ms</div>
          </div>
        </div>

        {/* Carrier Stats Table */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
          <div className="px-6 py-4 border-b border-gray-200">
            <h2 className="text-lg font-semibold text-gray-900">Carrier Performance</h2>
          </div>

          {stats.length === 0 ? (
            <div className="p-12 text-center">
              <p className="text-gray-500">No monitoring data available</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                      Carrier
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                      Health
                    </th>
                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">
                      Requests
                    </th>
                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">
                      Success Rate
                    </th>
                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">
                      Error Rate
                    </th>
                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">
                      Avg Response
                    </th>
                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">
                      Availability
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                      Last Request
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {stats.map(stat => {
                    const healthStatus = getHealthStatus(stat.carrierId);
                    const successRate = (stat.successfulRequests / stat.totalRequests) * 100;

                    return (
                      <tr key={stat.carrierId} className="hover:bg-gray-50">
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div className="text-sm font-medium text-gray-900">
                            {stat.carrierName}
                          </div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          {healthStatus && (
                            <span
                              className={`px-2 py-1 rounded-full text-xs font-medium ${getHealthColor(
                                healthStatus.status
                              )}`}
                            >
                              {healthStatus.status.toUpperCase()}
                            </span>
                          )}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-right text-sm text-gray-900">
                          {stat.totalRequests.toLocaleString()}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-right">
                          <span
                            className={`text-sm font-medium ${
                              successRate >= 95
                                ? 'text-green-600'
                                : successRate >= 80
                                  ? 'text-yellow-600'
                                  : 'text-red-600'
                            }`}
                          >
                            {successRate.toFixed(1)}%
                          </span>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-right">
                          <span
                            className={`text-sm font-medium ${
                              stat.errorRate < 5
                                ? 'text-green-600'
                                : stat.errorRate < 15
                                  ? 'text-yellow-600'
                                  : 'text-red-600'
                            }`}
                          >
                            {stat.errorRate.toFixed(1)}%
                          </span>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-right text-sm text-gray-900">
                          {stat.averageResponseTime.toFixed(0)}ms
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-right">
                          <span
                            className={`text-sm font-medium ${
                              stat.availability >= 99
                                ? 'text-green-600'
                                : stat.availability >= 95
                                  ? 'text-yellow-600'
                                  : 'text-red-600'
                            }`}
                          >
                            {stat.availability.toFixed(2)}%
                          </span>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                          {stat.lastRequestAt
                            ? new Date(stat.lastRequestAt).toLocaleString()
                            : 'Never'}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* Health Alerts */}
        {health.some(h => h.errors.length > 0) && (
          <div className="mt-8">
            <div className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
              <div className="px-6 py-4 border-b border-gray-200 bg-red-50">
                <h2 className="text-lg font-semibold text-red-900">Active Alerts</h2>
              </div>
              <div className="divide-y divide-gray-200">
                {health
                  .filter(h => h.errors.length > 0)
                  .map(healthCheck => (
                    <div key={healthCheck.carrierId} className="p-6">
                      <div className="flex items-start justify-between mb-2">
                        <div className="text-sm font-medium text-gray-900">
                          {stats.find(s => s.carrierId === healthCheck.carrierId)?.carrierName ||
                            'Unknown Carrier'}
                        </div>
                        <span
                          className={`px-2 py-1 rounded-full text-xs font-medium ${getHealthColor(
                            healthCheck.status
                          )}`}
                        >
                          {healthCheck.status.toUpperCase()}
                        </span>
                      </div>
                      <ul className="space-y-1">
                        {healthCheck.errors.map((error: string, index: number) => (
                          <li key={index} className="text-sm text-red-600">
                            • {error}
                          </li>
                        ))}
                      </ul>
                    </div>
                  ))}
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};
