import { useState, useEffect } from 'react';

const HealthCheck = () => {
  const [status, setStatus] = useState<'loading' | 'online' | 'offline'>('loading');

  useEffect(() => {
    const checkHealth = async () => {
      try {
        const response = await fetch('/api/health');
        const data = await response.json();
        setStatus(data.status === 'ok' ? 'online' : 'offline');
      } catch (error) {
        setStatus('offline');
      }
    };

    checkHealth();
    
    const interval = setInterval(checkHealth, 30000);
    return () => clearInterval(interval);
  }, []);

  const getStatusStyles = () => {
    switch (status) {
      case 'online':
        return { backgroundColor: '#deffde', padding: '1rem', borderRadius: '4px' };
      case 'offline':
        return { backgroundColor: '#ffeded', padding: '1rem', borderRadius: '4px' };
      default:
        return { backgroundColor: '#f3f3f3', padding: '1rem', borderRadius: '4px' };
    }
  };

  const getStatusMessage = () => {
    switch (status) {
      case 'online':
        return '✅ Le backend est accessible et fonctionne correctement';
      case 'offline':
        return '❌ Le backend n\'est pas accessible';
      default:
        return '⏳ Vérification de la connexion avec le backend...';
    }
  };

  return (
    <div style={{ padding: '1rem' }}>
      <div style={getStatusStyles()}>
        {status === 'loading' && (
          <span style={{ display: 'inline-block', animation: 'spin 1s linear infinite' }}>🔄</span>
        )}
        <span style={{ marginLeft: status === 'loading' ? '8px' : '0' }}>
          {getStatusMessage()}
        </span>
      </div>
    </div>
  );
};

export default HealthCheck;