import { Component, ReactNode } from 'react'

type Props = { 
  children: ReactNode
  fallback?: ReactNode
  onRetry?: () => void
  showRetry?: boolean
}
type State = { hasError: boolean }

export class ErrorBoundary extends Component<Props, State> {
  state: State = { hasError: false }

  static getDerivedStateFromError() {
    return { hasError: true }
  }

  componentDidCatch() {}

  handleRetry = () => {
    this.setState({ hasError: false })
    if (this.props.onRetry) {
      this.props.onRetry()
    }
  }

  render() {
    if (this.state.hasError) {
      if (this.props.fallback) {
        return this.props.fallback
      }
      
      return (
        <div className="p-6">
          <div className="bg-red-50 border border-red-200 rounded-md p-4">
            <div className="flex">
              <div className="flex-shrink-0">
                <svg className="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
                  <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                </svg>
              </div>
              <div className="ml-3 flex-1">
                <h3 className="text-sm font-medium text-red-800">Something went wrong loading this section</h3>
                <div className="mt-2 text-sm text-red-700">
                  <p>An error occurred while loading this component. Please try reloading it.</p>
                </div>
                {(this.props.showRetry !== false) && (
                  <div className="mt-4">
                    <button
                      onClick={this.handleRetry}
                      className="bg-red-100 px-4 py-2 rounded-md text-sm font-medium text-red-800 hover:bg-red-200 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2"
                    >
                      Reload Module
                    </button>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      )
    }
    return this.props.children
  }
}



