import { Component, ErrorInfo, ReactNode } from 'react';
import { AlertTriangle } from 'lucide-react';

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

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

/**
 * ErrorBoundary component to catch and handle React errors gracefully.
 *
 * Primarily used to catch JSONB parsing errors in pattern detection components
 * without crashing the entire InfoCenter UI.
 *
 * @example
 * ```tsx
 * <ErrorBoundary
 *   fallback={<div>Unable to display pattern data</div>}
 *   onError={(error) => console.error('Pattern error:', error)}
 * >
 *   <PatternDetectionSection />
 * </ErrorBoundary>
 * ```
 */
export class ErrorBoundary extends Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = { hasError: false, error: null };
  }

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

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error('ErrorBoundary caught error:', error, errorInfo);
    this.props.onError?.(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      if (this.props.fallback) {
        return this.props.fallback;
      }

      return (
        <div className="p-6 border border-red-200 bg-red-50 rounded-lg">
          <div className="flex items-center gap-3 mb-3">
            <AlertTriangle className="w-6 h-6 text-red-600" />
            <h3 className="text-lg font-semibold text-red-900">
              Something went wrong
            </h3>
          </div>
          <p className="text-red-700 mb-2">
            Unable to display this content due to a data parsing error.
          </p>
          <details className="text-sm">
            <summary className="cursor-pointer text-red-600 mb-2">
              Error details
            </summary>
            <pre className="bg-red-100 p-2 rounded overflow-auto">
              {this.state.error?.message}
            </pre>
          </details>
          <button
            onClick={() => this.setState({ hasError: false, error: null })}
            className="mt-4 px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700"
          >
            Try Again
          </button>
        </div>
      );
    }

    return this.props.children;
  }
}
