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

interface Props {
  children: ReactNode;
}
interface State {
  hasError: boolean;
  error: Error | null;
}

export default class ErrorBoundary extends Component<Props, State> {
  state: State = { hasError: false, error: null };

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

  componentDidCatch(error: Error, info: ErrorInfo) {
    console.error("ErrorBoundary caught:", error, info);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div
          className="admin-empty-state"
          style={{ minHeight: "60vh", justifyContent: "center" }}
        >
          <h2>Něco se pokazilo</h2>
          <p>{this.state.error?.message}</p>
          <button
            className="admin-btn admin-btn-primary"
            onClick={() => window.location.reload()}
          >
            Obnovit stránku
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}
