'use client';

import { useQuery } from '@tanstack/react-query';
import { RefreshCw, GitBranch, AlertCircle } from 'lucide-react';
import { api } from '@/lib/api';
import { ServiceMapGraph } from '@/components/services/ServiceMapGraph';

interface Service {
  name: string;
  type?: string;
  span_count: number;
  error_count: number;
  avg_duration_ms: number;
  first_seen: string;
  last_seen: string;
}

interface Dependency {
  source: string;
  target: string;
  call_count: number;
  error_count: number;
  avg_duration_ms: number;
}

interface ServiceMap {
  services: Service[];
  dependencies: Dependency[];
  updated_at: string;
}

export default function ServicesPage() {
  const { data: serviceMap, isLoading, refetch } = useQuery({
    queryKey: ['services', 'map'],
    queryFn: () => api.get('/api/v1/services/map'),
    refetchInterval: 60000,
  });

  const services: Service[] = serviceMap?.services ?? [];
  const dependencies: Dependency[] = serviceMap?.dependencies ?? [];

  const totalCalls = dependencies.reduce((sum, d) => sum + d.call_count, 0);
  const totalErrors = dependencies.reduce((sum, d) => sum + d.error_count, 0);
  const errorRate = totalCalls > 0 ? (totalErrors / totalCalls) * 100 : 0;

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Service Map</h1>
          <p className="text-sm text-gray-400 mt-1">
            Visualize dependencies between services
          </p>
        </div>
        <button
          onClick={() => refetch()}
          className="flex items-center gap-2 px-4 py-2 bg-gray-800 hover:bg-gray-700 text-white rounded-lg transition-colors"
        >
          <RefreshCw className={`h-4 w-4 ${isLoading ? 'animate-spin' : ''}`} />
          Refresh
        </button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <StatCard
          label="Services"
          value={services.length}
          icon={<GitBranch className="h-5 w-5 text-indigo-400" />}
        />
        <StatCard
          label="Dependencies"
          value={dependencies.length}
          icon={<GitBranch className="h-5 w-5 text-blue-400" />}
        />
        <StatCard
          label="Total Calls (24h)"
          value={totalCalls.toLocaleString()}
          icon={<GitBranch className="h-5 w-5 text-green-400" />}
        />
        <StatCard
          label="Error Rate"
          value={`${errorRate.toFixed(2)}%`}
          icon={<AlertCircle className={`h-5 w-5 ${errorRate > 5 ? 'text-red-400' : 'text-gray-400'}`} />}
        />
      </div>

      {/* Service Map Visualization */}
      <div className="bg-gray-900/50 rounded-lg border border-gray-800 p-4" style={{ height: '500px' }}>
        {services.length > 0 ? (
          <ServiceMapGraph services={services} dependencies={dependencies} />
        ) : (
          <div className="flex items-center justify-center h-full text-gray-500">
            {isLoading ? 'Loading service map...' : 'No services discovered yet'}
          </div>
        )}
      </div>

      {/* Services Table */}
      <div className="bg-gray-900/50 rounded-lg border border-gray-800 overflow-hidden">
        <div className="p-4 border-b border-gray-800">
          <h2 className="text-lg font-semibold text-white">Services</h2>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-gray-800">
                <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">Service</th>
                <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">Spans</th>
                <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">Errors</th>
                <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">Avg Duration</th>
                <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">Last Seen</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-800">
              {services.map((svc) => (
                <tr key={svc.name} className="hover:bg-gray-800/50">
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <div className="w-2 h-2 bg-green-500 rounded-full" />
                      <span className="text-white font-medium">{svc.name}</span>
                    </div>
                  </td>
                  <td className="px-4 py-3 text-gray-300">
                    {svc.span_count.toLocaleString()}
                  </td>
                  <td className="px-4 py-3">
                    <span className={svc.error_count > 0 ? 'text-red-400' : 'text-gray-400'}>
                      {svc.error_count.toLocaleString()}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-gray-300">
                    {svc.avg_duration_ms?.toFixed(2)} ms
                  </td>
                  <td className="px-4 py-3 text-gray-400 text-sm">
                    {new Date(svc.last_seen).toLocaleString()}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

function StatCard({ label, value, icon }: { label: string; value: number | string; icon: React.ReactNode }) {
  return (
    <div className="bg-gray-900/50 rounded-lg border border-gray-800 p-4">
      <div className="flex items-center justify-between">
        <span className="text-sm text-gray-400">{label}</span>
        {icon}
      </div>
      <p className="text-2xl font-bold text-white mt-2">{value}</p>
    </div>
  );
}
