/**
 * PlaylistErrorBoundary - Composant pour capturer les erreurs dans les composants de playlist
 * T0502: Create Playlist Error Handling Improvements
 */

import { Component, ErrorInfo, ReactNode } from 'react';
import { logger } from '@/utils/logger';
import { ErrorDisplay } from '@/components/ui/ErrorDisplay';
import { useNavigate } from 'react-router-dom';

interface Props {
  children: ReactNode;
  fallback?: ReactNode;
  onError?: (error: Error, errorInfo: ErrorInfo) => void;
}

interface State {
  hasError: boolean;
  error: Error | null;
  errorInfo: ErrorInfo | null;
}

/**
 * PlaylistErrorBoundary - Boundary pour capturer les erreurs dans les composants de playlist
 * T0502: Create Playlist Error Handling Improvements
 */
export class PlaylistErrorBoundary extends Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = {
      hasError: false,
      error: null,
      errorInfo: null,
    };
  }

  static getDerivedStateFromError(error: Error): Partial<State> {
    return {
      hasError: true,
      error,
    };
  }

  override componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    // Log l'erreur pour le debugging
    logger.error('PlaylistErrorBoundary caught an error', {
      error: error.message,
      stack: error.stack,
      componentStack: errorInfo.componentStack,
    });

    this.setState({
      error,
      errorInfo,
    });

    // Appeler le callback si fourni
    if (this.props.onError) {
      this.props.onError(error, errorInfo);
    }
  }

  handleReset = () => {
    this.setState({
      hasError: false,
      error: null,
      errorInfo: null,
    });
  };

  override render() {
    if (this.state.hasError) {
      // Si un fallback personnalisé est fourni, l'utiliser
      if (this.props.fallback) {
        return this.props.fallback;
      }

      // Sinon, afficher l'UI d'erreur par défaut
      return (
        <ErrorFallback error={this.state.error} onReset={this.handleReset} />
      );
    }

    return this.props.children;
  }
}

/**
 * ErrorFallback - Composant pour afficher l'erreur
 * T0502: Create Playlist Error Handling Improvements
 * Uses ErrorDisplay component for consistent error presentation
 */
function ErrorFallback({
  error,
  onReset,
}: {
  error: Error | null;
  onReset: () => void;
}) {
  const navigate = useNavigate();

  if (!error) {
    return null;
  }

  return (
    <div className="flex items-center justify-center min-h-[400px] p-4">
      <div className="w-full max-w-md">
        <ErrorDisplay
          error={error}
          variant="card"
          severity="error"
          title="Erreur de chargement"
          context={{
            action: 'loading playlist',
            resource: 'playlist',
          }}
          onRetry={onReset}
          actions={[
            {
              label: 'Retour aux playlists',
              onClick: () => navigate('/playlists'),
              variant: 'outline',
            },
          ]}
          showDetails={import.meta.env.DEV}
          dismissible={false}
        />
      </div>
    </div>
  );
}
