import posthog from "posthog-js";
import { Component, type ErrorInfo, type ReactNode } from "react";
import { announceUpdate, isStaleChunkError } from "../lib/update-notice";

export type ErrorBoundaryProps = {
  children: ReactNode;
  fallback: (state: { staleChunk: boolean }) => ReactNode;
  fullScreen?: boolean;
  resetOn?: unknown;
};

export type ErrorBoundaryState = { error: Error | undefined };

export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
  state: ErrorBoundaryState = { error: undefined };

  reportedMessage: string | undefined;

  static getDerivedStateFromError(error: Error): ErrorBoundaryState {
    return { error };
  }

  componentDidCatch(error: Error, info: ErrorInfo) {
    if (isStaleChunkError(error)) {
      announceUpdate(this.props.fullScreen ? "screen" : "toast");

      return;
    }

    if (posthog.__loaded && this.reportedMessage !== error.message) {
      this.reportedMessage = error.message;
      posthog.captureException(error, { componentStack: info.componentStack });
    }
  }

  componentDidUpdate(previous: ErrorBoundaryProps) {
    const { error } = this.state;

    if (!error || isStaleChunkError(error)) return;

    if (!Object.is(previous.resetOn, this.props.resetOn)) this.setState({ error: undefined });
  }

  render() {
    const { error } = this.state;

    return error ? this.props.fallback({ staleChunk: isStaleChunkError(error) }) : this.props.children;
  }
}
