import React, { useState, useEffect } from 'react';
import { RotateCcw, CheckCircle, AlertCircle, Clock, Zap } from 'lucide-react';

export default function Dashboard() {
  const [services, setServices] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [lastUpdated, setLastUpdated] = useState(null);

  const fetchServiceStatus = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await fetch('/mcp/status');

      if (!response.ok) {
        throw new Error('Failed to fetch service status');
      }

      const data = await response.json();
      setServices(data.services || []);
      setLastUpdated(new Date());
    } catch (err) {
      console.error('Error fetching status:', err);
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchServiceStatus();
    // Auto-refresh every 30 seconds
    const interval = setInterval(fetchServiceStatus, 30000);
    return () => clearInterval(interval);
  }, []);

  const getStatusIcon = (status) => {
    if (status === 'healthy') {
      return <CheckCircle className="w-5 h-5 text-green-500" />;
    } else if (status === 'warning') {
      return <AlertCircle className="w-5 h-5 text-yellow-500" />;
    } else {
      return <AlertCircle className="w-5 h-5 text-red-500" />;
    }
  };

  const getStatusBgColor = (status) => {
    if (status === 'healthy') return 'bg-green-50 border-green-200';
    if (status === 'warning') return 'bg-yellow-50 border-yellow-200';
    return 'bg-red-50 border-red-200';
  };

  const getStatusTextColor = (status) => {
    if (status === 'healthy') return 'text-green-700';
    if (status === 'warning') return 'text-yellow-700';
    return 'text-red-700';
  };

  const totalTools = services.reduce((sum, service) => sum + (service.toolCount || 0), 0);

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 p-8">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="flex items-center justify-between mb-8">
          <div>
            <h1 className="text-4xl font-bold text-slate-900 mb-2">MCP Gateway Dashboard</h1>
            <p className="text-slate-600">Real-time status and monitoring of all MCP services</p>
          </div>
          <button
            onClick={fetchServiceStatus}
            disabled={loading}
            className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:bg-blue-400 transition-colors"
          >
            <RotateCcw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
            Refresh
          </button>
        </div>

        {/* Summary Stats */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
          <div className="bg-white rounded-lg shadow p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-slate-600 text-sm font-medium">Total Services</p>
                <p className="text-3xl font-bold text-slate-900 mt-1">{services.length}</p>
              </div>
              <Zap className="w-8 h-8 text-blue-500" />
            </div>
          </div>

          <div className="bg-white rounded-lg shadow p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-slate-600 text-sm font-medium">Total Tools</p>
                <p className="text-3xl font-bold text-slate-900 mt-1">{totalTools}</p>
              </div>
              <Zap className="w-8 h-8 text-green-500" />
            </div>
          </div>

          <div className="bg-white rounded-lg shadow p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-slate-600 text-sm font-medium">Healthy Services</p>
                <p className="text-3xl font-bold text-slate-900 mt-1">
                  {services.filter(s => s.status === 'healthy').length}
                </p>
              </div>
              <CheckCircle className="w-8 h-8 text-green-500" />
            </div>
          </div>
        </div>

        {/* Last Updated */}
        {lastUpdated && (
          <div className="text-sm text-slate-600 mb-6 flex items-center gap-2">
            <Clock className="w-4 h-4" />
            Last updated: {lastUpdated.toLocaleTimeString()}
          </div>
        )}

        {/* Error State */}
        {error && (
          <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-8 text-red-700">
            <p className="font-medium">Error loading service status</p>
            <p className="text-sm">{error}</p>
          </div>
        )}

        {/* Services Grid */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {services.map((service) => (
            <div
              key={service.name}
              className={`rounded-lg border-2 p-6 transition-all hover:shadow-lg ${getStatusBgColor(service.status)}`}
            >
              {/* Service Header */}
              <div className="flex items-start justify-between mb-4">
                <div>
                  <h3 className="text-lg font-bold text-slate-900 capitalize">
                    {service.name}
                  </h3>
                  <p className={`text-sm font-medium ${getStatusTextColor(service.status)}`}>
                    {service.status.charAt(0).toUpperCase() + service.status.slice(1)}
                  </p>
                </div>
                {getStatusIcon(service.status)}
              </div>

              {/* Service Details */}
              <div className="space-y-3">
                {/* Tool Count */}
                <div className="flex items-center justify-between p-3 bg-white rounded border border-slate-200">
                  <span className="text-sm text-slate-600">Tools Available</span>
                  <span className="text-xl font-bold text-slate-900">{service.toolCount || 0}</span>
                </div>

                {/* Response Time */}
                {service.responseTime !== undefined && (
                  <div className="flex items-center justify-between p-3 bg-white rounded border border-slate-200">
                    <span className="text-sm text-slate-600">Response Time</span>
                    <span className="text-sm font-mono font-bold text-slate-900">
                      {service.responseTime}ms
                    </span>
                  </div>
                )}

                {/* URL */}
                <div className="p-3 bg-white rounded border border-slate-200 text-xs">
                  <p className="text-slate-600 mb-1">Service URL</p>
                  <p className="text-slate-900 font-mono break-all">{service.url}</p>
                </div>

                {/* Last Check */}
                {service.lastCheck && (
                  <div className="text-xs text-slate-600 px-3">
                    Last health check: {new Date(service.lastCheck).toLocaleTimeString()}
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>

        {/* Empty State */}
        {!loading && services.length === 0 && !error && (
          <div className="text-center py-12">
            <p className="text-slate-600">No services available yet. Check your configuration.</p>
          </div>
        )}

        {/* Loading State */}
        {loading && services.length === 0 && (
          <div className="text-center py-12">
            <div className="inline-block">
              <div className="w-8 h-8 border-4 border-slate-300 border-t-blue-600 rounded-full animate-spin"></div>
            </div>
            <p className="text-slate-600 mt-4">Loading service status...</p>
          </div>
        )}
      </div>
    </div>
  );
}
