import { Component, ReactNode } from 'react';
import { Alert, Button } from 'antd';

interface Props {
  children: ReactNode;
  serviceName: string;
}

interface State {
  hasError: boolean;
  error?: Error;
}

/**
 * Error boundary for iframe components
 * Prevents iframe loading failures from crashing the entire page
 */
export class IframeErrorBoundary extends Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = { hasError: false };
  }

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

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    console.error('Iframe loading error:', error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
        <Alert
          message={`Failed to load ${this.props.serviceName}`}
          description={this.state.error?.message || 'Unknown error occurred'}
          type="error"
          showIcon
          action={
            <Button
              size="small"
              onClick={() => window.location.reload()}
            >
              Reload Page
            </Button>
          }
          style={{ marginBottom: 16 }}
        />
      );
    }

    return this.props.children;
  }
}
