import React, { Component, ErrorInfo, ReactNode } from "react";

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

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

class ErrorBoundary extends Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = { hasError: false };
  }

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

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    this.setState({
      error,
      errorInfo,
    });

    if (process.env.NODE_ENV === "development") {
      console.error("Error caught by ErrorBoundary:", error);
      console.error("Error info:", errorInfo);
    }

    if (process.env.NODE_ENV === "production") {
      // Example: Sentry.captureException(error);
    }
  }

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

      return (
        <div style={{ padding: "20px", textAlign: "center" }}>
          <h2>Something went wrong</h2>
          {process.env.NODE_ENV === "development" && (
            <div style={{ textAlign: "left", marginTop: "20px" }}>
              <details style={{ whiteSpace: "pre-wrap" }}>
                <summary>Error Details (Development Only)</summary>
                <p>
                  <strong>Error:</strong> {this.state.error?.toString()}
                </p>
                <p>
                  <strong>Stack:</strong> {this.state.error?.stack}
                </p>
                <p>
                  <strong>Component Stack:</strong>{" "}
                  {this.state.errorInfo?.componentStack}
                </p>
              </details>
            </div>
          )}
          <button
            onClick={() => window.location.reload()}
            style={{ marginTop: "20px", padding: "10px 20px" }}
          >
            Reload Page
          </button>
        </div>
      );
    }

    return this.props.children;
  }
}

export default ErrorBoundary;
