import React, { useEffect, useState } from 'react'; import { AlertCircle, X, RefreshCw, WifiOff } from 'lucide-react'; import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'; import { Button } from '@/components/ui/button'; import { checkApiConnection } from '@/lib/api'; import { API_BASE_URL } from '@/config'; import apiClient from '@/lib/api/axios-instance'; const ApiConnectionAlert = () => { const [isApiAvailable, setIsApiAvailable] = useState(null); const [checking, setChecking] = useState(false); const [isVisible, setIsVisible] = useState(true); const [retryCount, setRetryCount] = useState(0); const [fadeOut, setFadeOut] = useState(false); const checkConnection = async () => { setChecking(true); try { console.log('Checking API connection...'); const isAvailable = await checkApiConnection(); console.log('API connection check result:', isAvailable); setIsApiAvailable(isAvailable); if (isAvailable) { // If connection is restored after previous failures, show success briefly then hide if (retryCount > 0) { setTimeout(() => { setFadeOut(true); setTimeout(() => setIsVisible(false), 300); }, 3000); } } else { setRetryCount(prev => prev + 1); } } catch (error) { console.error('Error checking API connection:', error); setIsApiAvailable(false); setRetryCount(prev => prev + 1); } finally { setChecking(false); } }; useEffect(() => { checkConnection(); // Set up automatic retry every 30 seconds if API is down const intervalId = setInterval(() => { if (isApiAvailable === false) { checkConnection(); } }, 30000); return () => clearInterval(intervalId); }, [isApiAvailable]); const closeAlert = () => { setFadeOut(true); setTimeout(() => setIsVisible(false), 300); }; if (isApiAvailable === true && !isVisible) { return null; } return ( <> {(isApiAvailable === false || (isApiAvailable === true && retryCount > 0)) && isVisible && (
{isApiAvailable === true ? (
API Connection Restored

Successfully connected to the API server. You can continue using the application.

) : (
API Connection Error

Cannot connect to the API server at {API_BASE_URL}. Some features may not work correctly.

Troubleshooting steps:

  • Ensure the API server is running
  • Check your network connection
  • Verify that ports are not blocked by a firewall
  • If you're a developer, check for CORS issues
)}
)} ); }; export default ApiConnectionAlert;