'use client';

import { useQuery } from '@tanstack/react-query';
import { AlertTriangle, CheckCircle, Clock } from 'lucide-react';
import { api } from '@/lib/api';
import { formatTime } from '@/lib/utils';

interface Alert {
  id: string;
  name: string;
  severity: string;
  status: string;
  service?: string;
  message: string;
  fired_at: string;
}

export function RecentAlerts() {
  const { data, isLoading } = useQuery({
    queryKey: ['alerts', 'recent'],
    queryFn: () => api.get('/api/v1/alerts', { limit: 5 }),
    refetchInterval: 30000,
  });

  const alerts: Alert[] = data?.alerts ?? [];

  const severityColors: Record<string, string> = {
    critical: 'text-red-400 bg-red-400/10 border-red-400/20',
    warning: 'text-yellow-400 bg-yellow-400/10 border-yellow-400/20',
    info: 'text-blue-400 bg-blue-400/10 border-blue-400/20',
  };

  return (
    <div className="bg-gray-900/50 rounded-lg border border-gray-800 p-4">
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-lg font-semibold text-white">Recent Alerts</h3>
        <a
          href="/alerts"
          className="text-sm text-indigo-400 hover:text-indigo-300"
        >
          View all →
        </a>
      </div>

      {isLoading ? (
        <div className="flex items-center justify-center py-8 text-gray-500">
          Loading...
        </div>
      ) : alerts.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-8 text-gray-500">
          <CheckCircle className="h-8 w-8 mb-2 text-green-400" />
          <p>No active alerts</p>
        </div>
      ) : (
        <div className="space-y-2">
          {alerts.map((alert) => (
            <div
              key={alert.id}
              className={`p-3 rounded-lg border ${
                severityColors[alert.severity] || severityColors.info
              }`}
            >
              <div className="flex items-start justify-between">
                <div className="flex items-center gap-2">
                  <AlertTriangle className="h-4 w-4" />
                  <span className="font-medium">{alert.name}</span>
                </div>
                <span className="text-xs opacity-75">
                  {alert.status === 'firing' ? '🔴' : '✅'} {alert.status}
                </span>
              </div>
              <p className="text-sm mt-1 opacity-75 line-clamp-2">
                {alert.message}
              </p>
              <div className="flex items-center gap-2 mt-2 text-xs opacity-50">
                <Clock className="h-3 w-3" />
                {formatTime(alert.fired_at)}
                {alert.service && (
                  <>
                    <span>•</span>
                    <span>{alert.service}</span>
                  </>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
