'use client';

import React, { Component, ReactNode } from 'react';
import Button from './Button';

interface Props {
  children: ReactNode;
  fallbackTitle?: string;
  fallbackMessage?: string;
  onReset?: () => void;
}

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

/**
 * Error Boundary Component
 * Catches JavaScript errors in child components and displays a fallback UI
 */
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 };
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    // Log error to console in development
    console.error('ErrorBoundary caught an error:', error, errorInfo);
  }

  handleReset = () => {
    this.setState({ hasError: false, error: null });
    this.props.onReset?.();
  };

  render() {
    if (this.state.hasError) {
      return (
        <div
          style={{
            padding: '2rem',
            textAlign: 'center',
            backgroundColor: 'rgba(248, 113, 113, 0.1)',
            border: '1px solid rgba(248, 113, 113, 0.35)',
            borderRadius: '8px',
            margin: '1rem 0',
          }}
        >
          <h3
            style={{
              fontSize: '1.125rem',
              fontWeight: 600,
              color: '#fecaca',
              marginBottom: '0.75rem',
            }}
          >
            {this.props.fallbackTitle || 'Something went wrong'}
          </h3>
          <p
            style={{
              color: '#fca5a5',
              marginBottom: '1rem',
              fontSize: '0.875rem',
            }}
          >
            {this.props.fallbackMessage ||
              'An error occurred while rendering this component. Please try again.'}
          </p>
          {/* Only show error details in development to avoid exposing internal paths */}
          {this.state.error && process.env.NODE_ENV === 'development' && (
            <details
              style={{
                textAlign: 'left',
                marginBottom: '1rem',
                fontSize: '0.75rem',
                color: '#f87171',
              }}
            >
              <summary style={{ cursor: 'pointer', marginBottom: '0.5rem' }}>
                Error details (dev only)
              </summary>
              <pre
                style={{
                  backgroundColor: 'rgba(0, 0, 0, 0.2)',
                  padding: '0.75rem',
                  borderRadius: '4px',
                  overflow: 'auto',
                  maxHeight: '200px',
                }}
              >
                {this.state.error.message}
                {'\n\n'}
                {this.state.error.stack}
              </pre>
            </details>
          )}
          <Button variant="secondary" size="sm" onClick={this.handleReset}>
            Try Again
          </Button>
        </div>
      );
    }

    return this.props.children;
  }
}

export default ErrorBoundary;
