import { Button } from '@learnitive/ui-components';
import React from 'react';

type State = { error?: Error };

export class PaperMemoryErrorBoundary extends React.Component<{
  wsName: string;
  children: React.ReactNode;
}, State> {
  state: State = {};

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

  componentDidUpdate(previous: Readonly<{ wsName: string; children: React.ReactNode }>): void {
    if (previous.wsName !== this.props.wsName && this.state.error) this.setState({ error: undefined });
  }

  componentDidCatch(error: Error): void {
    console.error('Paper Memory UI crashed', error);
  }

  render(): React.ReactNode {
    if (!this.state.error) return this.props.children;
    return (
      <div className="flex min-h-0 flex-1 items-center justify-center p-6" data-testid="paper-memory-error-boundary">
        <div className="max-w-sm rounded-lg border border-destructive/30 bg-destructive/5 p-4 text-sm">
          <div className="font-medium">Papers could not be displayed.</div>
          <p className="mt-1 text-xs text-muted-foreground">Your local paper library was not deleted. Reload this panel to retry.</p>
          <Button className="mt-3" size="sm" variant="outline" onClick={() => this.setState({ error: undefined })}>Retry</Button>
        </div>
      </div>
    );
  }
}
