"use client";

import { Component, ReactNode } from "react";

type Props = {
  fallback?: ReactNode;
  children: ReactNode;
};

type State = {
  hasError: boolean;
  error: Error | null;
};

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

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

  render() {
    if (this.state.hasError) {
      return (
        this.props.fallback ?? (
          <div className="flex min-h-[200px] items-center justify-center rounded-lg border border-red-200 bg-red-50 p-6 text-center">
            <div>
              <p className="mb-2 font-semibold text-red-700">
                Something went wrong
              </p>
              <p className="text-sm text-red-600">
                Please refresh the page or try again later
              </p>
            </div>
          </div>
        )
      );
    }

    return this.props.children;
  }
}
