import React, { Component } from 'react';
import { Container, Alert, Button, Card } from 'react-bootstrap';
import { FaExclamationTriangle, FaHome } from 'react-icons/fa';
import { Link } from 'react-router-dom';

class ErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = {
      hasError: false,
      error: null,
      errorInfo: null
    };
  }

  static getDerivedStateFromError(error) {
    // Update state so the next render shows the fallback UI
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // Log the error to an error reporting service
    console.error('Error caught by ErrorBoundary:', error, errorInfo);
    this.setState({
      error: error,
      errorInfo: errorInfo
    });
  }

  render() {
    if (this.state.hasError) {
      // Fallback UI when an error occurs
      return (
        <Container className="mt-5">
          <Card className="shadow-sm">
            <Card.Body className="text-center py-5">
              <FaExclamationTriangle size={50} className="text-danger mb-3" />
              <h2 className="mb-3">Something went wrong</h2>
              <Alert variant="danger" className="mb-4">
                {this.state.error && this.state.error.toString()}
              </Alert>
              <p className="mb-4">
                We apologize for the inconvenience. Please try refreshing the page or returning to the dashboard.
              </p>
              <div className="d-flex justify-content-center gap-3">
                <Button 
                  as={Link} 
                  to="/dashboard" 
                  variant="primary"
                >
                  <FaHome className="me-2" />
                  Back to Dashboard
                </Button>
                <Button 
                  variant="outline-secondary" 
                  onClick={() => window.location.reload()}
                >
                  Refresh Page
                </Button>
              </div>
            </Card.Body>
          </Card>
          
          {process.env.NODE_ENV === 'development' && this.state.errorInfo && (
            <Card className="mt-4 shadow-sm">
              <Card.Header className="bg-light">
                <h5 className="mb-0">Developer Details</h5>
              </Card.Header>
              <Card.Body>
                <details style={{ whiteSpace: 'pre-wrap' }}>
                  <summary>Error Stack</summary>
                  {this.state.error && this.state.error.toString()}
                  <br />
                  {this.state.errorInfo.componentStack}
                </details>
              </Card.Body>
            </Card>
          )}
        </Container>
      );
    }

    // If no error occurred, render children normally
    return this.props.children;
  }
}

export default ErrorBoundary;
