'use client';

import React, { Component, type ReactNode } from 'react';

import { Card, CardContent } from '@/components/ui/card';

interface Props {
  children: ReactNode;
  fallback?: ReactNode;
}

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

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

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

  reset = () => {
    this.setState({ hasError: false, error: null });
  };

  render() {
    if (this.state.hasError) {
      if (this.props.fallback) {
        return this.props.fallback;
      }

      return (
        <Card>
          <CardContent className="flex flex-col items-center justify-center gap-3 py-8">
            <p className="text-sm text-muted-foreground">Widget unavailable</p>
            <button
              onClick={this.reset}
              className="text-xs text-muted-foreground underline-offset-2 hover:underline"
            >
              Retry
            </button>
          </CardContent>
        </Card>
      );
    }

    return this.props.children;
  }
}
