import { useEffect, useState } from 'react';
import { useErrorHandler } from '../../hooks/useErrorHandler';

export default function GlobalErrorDisplay() {
  const { errors, clearError, clearAllErrors } = useErrorHandler('GlobalErrorDisplay');
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    setIsVisible(errors.length > 0);
  }, [errors.length]);

  if (!isVisible || errors.length === 0) {
    return null;
  }

  return (
    <div className="fixed top-4 right-4 z-[9999] max-w-md space-y-2">
      {errors.map((error, index) => (
        <div
          key={index}
          className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg shadow-lg p-4 animate-in slide-in-from-right"
        >
          <div className="flex items-start justify-between gap-2">
            <div className="flex-1">
              <div className="flex items-center gap-2 mb-1">
                <span className="text-red-600 dark:text-red-400 text-lg">⚠️</span>
                <span className="text-sm font-semibold text-red-800 dark:text-red-200">
                  {error.source}
                </span>
              </div>
              <p className="text-sm text-red-700 dark:text-red-300 mb-2">
                {error.message}
              </p>
              {error.stack && (
                <details className="mt-2">
                  <summary className="text-xs text-red-600 dark:text-red-400 cursor-pointer hover:underline">
                    Show stack trace
                  </summary>
                  <pre className="mt-2 text-xs bg-red-100 dark:bg-red-900/40 p-2 rounded overflow-auto max-h-32">
                    {error.stack}
                  </pre>
                </details>
              )}
            </div>
            <button
              onClick={() => clearError(index)}
              className="text-red-600 dark:text-red-400 hover:text-red-800 dark:hover:text-red-200 text-xl leading-none"
              aria-label="Dismiss error"
            >
              ×
            </button>
          </div>
        </div>
      ))}
      {errors.length > 1 && (
        <button
          onClick={clearAllErrors}
          className="w-full px-3 py-2 text-xs bg-red-600 text-white rounded hover:bg-red-700"
        >
          Clear All Errors
        </button>
      )}
    </div>
  );
}

