import { Component, type ErrorInfo, type ReactNode } from "react";
import { AlertCircle, RefreshCw } from 'lucide-react';

interface Props {
  children: ReactNode;
  fallback?: ReactNode;
}

interface State {
  error: Error | null;
}

export class MessageBoundary extends Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = { error: null };
  }

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

  componentDidCatch(error: Error, info: ErrorInfo) {
    console.warn('MessageBoundary caught:', error.message, info.componentStack);
  }

  handleRetry = () => {
    this.setState({ error: null });
  };

  render() {
    if (this.state.error) {
      if (this.props.fallback !== undefined) {
        return <>{this.props.fallback}</>;
      }
      return (
        <div className="flex items-center gap-2 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs">
          <AlertCircle className="size-3.5 text-destructive shrink-0" />
          <span className="text-muted-foreground flex-1">Rendering failed</span>
          <button
            type="button"
            onClick={this.handleRetry}
            className="inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-foreground hover:bg-muted"
            aria-label="Retry rendering"
            title="Retry"
          >
            <RefreshCw className="size-3" />
            Retry
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}
