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

interface Props {
  children?: ReactNode;
  componentName?: string;
}

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

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

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

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error(`react_phx: Error in component "${this.props.componentName}":`, error, errorInfo);
  }

  componentDidUpdate(prevProps: Props) {
    if (prevProps.children !== this.props.children) {
      this.setState({ hasError: false, error: null });
    }
  }

  render() {
    if (this.state.hasError) {
      const { error } = this.state;
      const { componentName } = this.props;
      return createElement(
        "div",
        {
          style: {
            padding: "16px",
            margin: "8px",
            background: "#fef2f2",
            border: "1px solid #fca5a5",
            borderRadius: "8px",
            color: "#991b1b",
            fontSize: "13px",
            fontFamily: "monospace",
          },
        },
        createElement("strong", null, `react_phx error in <${componentName || "Unknown"}>:`),
        createElement("pre", { style: { marginTop: "8px", whiteSpace: "pre-wrap", fontSize: "12px" } }, error?.message || "Unknown error"),
      );
    }
    return this.props.children;
  }
}
