'use client';

import React, { useState, useEffect } from 'react';
import { Badge } from '@/components/ui/badge';
import { CheckCircle, AlertCircle, RefreshCw, Zap } from 'lucide-react';
import quantumWeaverAPI from '@/lib/api-client';
import { SafeTimestamp } from './ClientTimeStampProvider';

interface BackendStatusIndicatorProps {
  className?: string;
}

export default function BackendStatusIndicator({ className }: BackendStatusIndicatorProps) {
  const [status, setStatus] = useState<'checking' | 'online' | 'offline'>('checking');
  const [lastCheck, setLastCheck] = useState<Date>(new Date());

  const checkBackendStatus = async () => {
    try {
      setStatus('checking');
      const health = await quantumWeaverAPI.healthCheck();
      setStatus(health.status === 'healthy' ? 'online' : 'offline');
      setLastCheck(new Date());
    } catch (error) {
      setStatus('offline');
      setLastCheck(new Date());
    }
  };

  useEffect(() => {
    // Initial check
    checkBackendStatus();

    // Check every 30 seconds
    const interval = setInterval(checkBackendStatus, 30000);

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

  const getStatusBadge = () => {
    switch (status) {
      case 'online':
        return (
          <Badge className="bg-[#39ff14]/20 text-[#39ff14] border-[#39ff14]/30">
            <CheckCircle className="w-3 h-3 mr-1" />
            Backend Online
          </Badge>
        );
      case 'offline':
        return (
          <Badge className="bg-red-500/20 text-red-400 border-red-500/30">
            <AlertCircle className="w-3 h-3 mr-1" />
            Backend Offline
          </Badge>
        );
      case 'checking':
        return (
          <Badge className="bg-blue-500/20 text-blue-400 border-blue-500/30">
            <RefreshCw className="w-3 h-3 mr-1 animate-spin" />
            Checking...
          </Badge>
        );
    }
  };

  return (
    <div className={`flex items-center space-x-2 ${className}`}>
      {getStatusBadge()}
      <span className="text-xs text-muted-foreground">
        Last: <SafeTimestamp timestamp={lastCheck} format="time" />
      </span>
    </div>
  );
} 