import React, { useState, useEffect } from 'react';
import { checkHealth } from '../lib/api/health';
import type { HealthResponse } from '../lib/api/health';

/**
 * Component that displays the system health information
 */
export const HealthCheck: React.FC = () => {
  const [health, setHealth] = useState<HealthResponse | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchHealth = async () => {
      try {
        setLoading(true);
        const healthData = await checkHealth();
        setHealth(healthData);
        setError(null);
      } catch (err) {
        console.error('Error fetching health data:', err);
        setError('Failed to fetch health information');
      } finally {
        setLoading(false);
      }
    };

    fetchHealth();
  }, []);

  if (loading) {
    return <div className="p-4 text-center">Loading health information...</div>;
  }

  if (error) {
    return <div className="p-4 text-red-500">{error}</div>;
  }

  if (!health) {
    return <div className="p-4 text-yellow-500">No health information available</div>;
  }

  const systemHealth = health.entries['System Health'];

  return (
    <div className="p-4 border rounded-lg shadow-sm">
      <h2 className="text-xl font-semibold mb-4">
        System Health: 
        <span className={`ml-2 ${systemHealth.status === 'Healthy' ? 'text-green-500' : 'text-red-500'}`}>
          {systemHealth.status}
        </span>
      </h2>
      
      <div className="text-sm text-gray-600 mb-4">
        {systemHealth.description}
      </div>
      
      <div className="bg-gray-50 p-3 rounded">
        <h3 className="text-md font-medium mb-2">System Metrics</h3>
        
        <div className="grid grid-cols-2 gap-2">
          {Object.entries(systemHealth.data).map(([key, value]) => (
            <div key={key} className="flex justify-between border-b pb-1">
              <span className="font-medium">{key}:</span>
              <span>{String(value)}</span>
            </div>
          ))}
        </div>
      </div>
      
      <div className="mt-4 text-xs text-gray-500">
        Total Duration: {health.totalDuration}
      </div>
    </div>
  );
};

export default HealthCheck; 