import Button from '@/components/ui/Button.tsx';
import IconWrapper from '@/components/ui/IconWrapper.tsx';
import { XCircle } from 'lucide-react';
import { Component, ErrorInfo, ReactNode } from 'react';

interface Props {
  children?: ReactNode;
}

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

class ErrorBoundary extends Component<Props, State> {
  // FIX: Replaced constructor with a class property for state initialization. This is a more modern and robust approach in class components and resolves the reported errors regarding `this.state` and `this.props` not being available.
  state: State = {
    hasError: false,
    error: undefined,
  };

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

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error('Uncaught error:', error, errorInfo);
  }

  // FIX: Using an arrow function to automatically bind 'this'.
  handleRefresh = () => {
    window.location.reload();
  };

  render() {
    if (this.state.hasError) {
      return (
        <div className="flex flex-col items-center justify-center min-h-screen bg-background p-8 text-center">
          <IconWrapper className="bg-destructive/10 text-destructive">
            <XCircle className="h-8 w-8 text-current" />
          </IconWrapper>
          <h1 className="font-serif text-3xl font-bold text-destructive">Something went wrong</h1>
          <p className="mt-4 text-lg text-muted-foreground">We're sorry for the inconvenience. Please try refreshing the page.</p>
          <pre className="mt-4 text-sm text-left bg-muted p-4 rounded-md max-w-full overflow-auto">
            {this.state.error?.message || 'An unknown error occurred'}
          </pre>
          <Button onClick={this.handleRefresh} className="mt-6">
            Refresh Page
          </Button>
        </div>
      );
    }

    return this.props.children;
  }
}

export default ErrorBoundary;
