"use client";

import React from "react";

interface ErrorBoundaryState {
  hasError: boolean;
  error?: Error;
}

interface ErrorBoundaryProps {
  children: React.ReactNode;
  fallback?: React.ComponentType<{ error: Error; reset: () => void }>;
}

export class ErrorBoundary extends React.Component<
  ErrorBoundaryProps,
  ErrorBoundaryState
> {
  constructor(props: ErrorBoundaryProps) {
    super(props);
    this.state = { hasError: false };
  }

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

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    console.error("Error caught by boundary:", error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      const FallbackComponent = this.props.fallback || DefaultErrorFallback;
      return (
        <FallbackComponent
          error={this.state.error!}
          reset={() => this.setState({ hasError: false, error: undefined })}
        />
      );
    }

    return this.props.children;
  }
}

function DefaultErrorFallback({
  error,
  reset,
}: {
  error: Error;
  reset: () => void;
}) {
  return (
    <div
      style={{
        padding: "20px",
        margin: "20px",
        border: "1px solid #red",
        borderRadius: "8px",
        backgroundColor: "#fee",
        color: "#c00",
      }}
    >
      <h2>Something went wrong:</h2>
      <details style={{ whiteSpace: "pre-wrap" }}>
        <summary>Error details</summary>
        {error.message}
        {error.stack && (
          <pre style={{ marginTop: "10px", fontSize: "12px" }}>
            {error.stack}
          </pre>
        )}
      </details>
      <button
        onClick={reset}
        style={{
          marginTop: "10px",
          padding: "8px 16px",
          backgroundColor: "#c00",
          color: "white",
          border: "none",
          borderRadius: "4px",
          cursor: "pointer",
        }}
      >
        Try again
      </button>
    </div>
  );
}

export default ErrorBoundary;
