'use client';

import { useEffect, useState, useCallback } from 'react';
import { SidebarNav } from '@/components/sidebar-nav';
import { api } from '@/lib/api';
import type { Service, ServiceHealth } from '@/lib/api';
import { Activity, Clock, RefreshCw, TrendingUp } from 'lucide-react';
import { getStatusColor } from '@/lib/utils';

export default function HealthDashboardPage() {
  const [services, setServices] = useState<Service[]>([]);
  const [healthData, setHealthData] = useState<Map<string, ServiceHealth>>(new Map());
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

  const loadData = useCallback(async () => {
    try {
      const [servicesData, healthDataArray] = await Promise.all([
        api.getServices(),
        api.getHealth(),
      ]);

      setServices(servicesData);
      const healthMap = new Map(healthDataArray.map(h => [h.serviceId, h]));
      setHealthData(healthMap);
    } catch (error) {
      console.error('Failed to load data:', error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, []);

  const refreshHealth = useCallback(async () => {
    setRefreshing(true);
    try {
      await api.clearHealthCache();
      await loadData();
    } catch (error) {
      console.error('Failed to refresh health:', error);
    } finally {
      setRefreshing(false);
    }
  }, [loadData]);

  useEffect(() => {
    loadData();

    const interval = setInterval(() => {
      loadData();
    }, 30000);

    return () => clearInterval(interval);
  }, [loadData]);


  function getResponseTimeColor(responseTime?: number) {
    if (!responseTime) return 'text-gray-500';
    if (responseTime < 500) return 'text-green-600';
    if (responseTime < 1000) return 'text-yellow-600';
    return 'text-red-600';
  }

  function getUptimePercentage(service: Service): number {
    if (!service.lastHealthCheckAt) return 0;
    const lastCheck = new Date(service.lastHealthCheckAt).getTime();
    const now = Date.now();
    const timeDiff = now - lastCheck;
    if (timeDiff > 3600000) return 0;
    return Math.max(0, 100 - (timeDiff / 3600000) * 100);
  }

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-gray-600">Loading...</div>
      </div>
    );
  }

  const healthyCount = services.filter(s => s.status === 'up').length;
  const degradedCount = services.filter(s => s.status === 'degraded').length;
  const downCount = services.filter(s => s.status === 'down').length;

  return (
    <div className="flex min-h-screen bg-gray-50">
      <SidebarNav />

      <main className="flex-1 min-w-0 overflow-y-auto">
        <div className="p-8 max-md:p-4">
          <div className="mb-8 flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-gray-900">Health Dashboard</h1>
            <p className="text-sm text-gray-600">Real-time service health monitoring</p>
          </div>
          <button
            onClick={refreshHealth}
            disabled={refreshing}
            className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <RefreshCw className={`w-4 h-4 ${refreshing ? 'animate-spin' : ''}`} />
            Refresh
          </button>
        </div>
        {/* Summary Cards */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
          <div className="bg-white border border-gray-200 rounded-lg p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-500">Total Services</p>
                <p className="text-3xl font-bold text-gray-900">{services.length}</p>
              </div>
              <Activity className="w-8 h-8 text-blue-600" />
            </div>
          </div>

          <div className="bg-white border border-gray-200 rounded-lg p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-500">Healthy</p>
                <p className="text-3xl font-bold text-green-600">{healthyCount}</p>
              </div>
              <Activity className="w-8 h-8 text-green-600" />
            </div>
          </div>

          <div className="bg-white border border-gray-200 rounded-lg p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-500">Degraded</p>
                <p className="text-3xl font-bold text-yellow-600">{degradedCount}</p>
              </div>
              <Activity className="w-8 h-8 text-yellow-600" />
            </div>
          </div>

          <div className="bg-white border border-gray-200 rounded-lg p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-500">Down</p>
                <p className="text-3xl font-bold text-red-600">{downCount}</p>
              </div>
              <Activity className="w-8 h-8 text-red-600" />
            </div>
          </div>
        </div>

        {/* Health Details */}
        <div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
          <div className="px-6 py-4 border-b border-gray-200">
            <h2 className="text-lg font-semibold text-gray-900">Service Health Details</h2>
          </div>
          <div className="divide-y divide-gray-200">
            {services.map((service) => {
              const health = healthData.get(service.id);
              const uptime = getUptimePercentage(service);

              return (
                <div key={service.id} className="px-6 py-4">
                  <div className="flex items-start justify-between mb-4">
                    <div>
                      <h3 className="text-lg font-semibold text-gray-900">{service.name}</h3>
                      <p className="text-sm text-gray-500">{service.repoPath}</p>
                    </div>
                    <span className={`px-3 py-1 text-sm font-medium rounded-full border ${getStatusColor(service.status)}`}>
                      {service.status}
                    </span>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div className="flex items-center gap-3">
                      <Clock className="w-5 h-5 text-gray-400" />
                      <div>
                        <p className="text-sm text-gray-500">Last Check</p>
                        <p className="text-sm font-medium text-gray-900">
                          {service.lastHealthCheckAt
                            ? new Date(service.lastHealthCheckAt).toLocaleString()
                            : 'Never'}
                        </p>
                      </div>
                    </div>

                    {health?.responseTime && (
                      <div className="flex items-center gap-3">
                        <TrendingUp className="w-5 h-5 text-gray-400" />
                        <div>
                          <p className="text-sm text-gray-500">Response Time</p>
                          <p className={`text-sm font-medium ${getResponseTimeColor(health.responseTime)}`}>
                            {health.responseTime}ms
                          </p>
                        </div>
                      </div>
                    )}

                    <div className="flex items-center gap-3">
                      <Activity className="w-5 h-5 text-gray-400" />
                      <div>
                        <p className="text-sm text-gray-500">Estimated Uptime</p>
                        <p className="text-sm font-medium text-gray-900">{uptime.toFixed(1)}%</p>
                      </div>
                    </div>
                  </div>

                  <div className="mt-4">
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-sm text-gray-500">Uptime</span>
                      <span className="text-sm font-medium text-gray-900">{uptime.toFixed(1)}%</span>
                    </div>
                    <div className="w-full bg-gray-200 rounded-full h-2">
                      <div
                        className={`h-2 rounded-full ${
                          uptime > 90 ? 'bg-green-600' : uptime > 70 ? 'bg-yellow-600' : 'bg-red-600'
                        }`}
                        style={{ width: `${uptime}%` }}
                      />
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </main>
    </div>
  );
}
