import React, { type ReactNode, type ReactElement } from 'react';
import { motion } from 'framer-motion';

interface Props {
  children: ReactNode;
}

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

export class ErrorBoundary extends React.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) {
    console.error('Error caught by boundary:', error, errorInfo);
  }

  handleRetry = () => {
    this.setState({ hasError: false, error: null });
    window.location.href = '/';
  };

  render(): ReactElement {
    if (this.state.hasError) {
      return (
        <div className="min-h-screen bg-slate-900 flex items-center justify-center p-4">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6 }}
            className="max-w-lg w-full"
          >
            <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8">
              <div className="text-center">
                <h1 className="text-5xl font-bold text-red-400 mb-4">Oops!</h1>
                <p className="text-slate-300 mb-6">
                  Something went wrong. Our neural networks are recalibrating...
                </p>
                <div className="bg-slate-900/50 rounded-lg p-4 mb-6 max-h-48 overflow-y-auto">
                  <p className="text-xs text-slate-400 font-mono break-words">
                    {this.state.error?.message || 'Unknown error'}
                  </p>
                </div>
                <button
                  onClick={this.handleRetry}
                  className="w-full bg-sky-500 hover:bg-sky-600 text-white font-semibold py-3 rounded-lg transition-colors duration-200"
                >
                  Return Home
                </button>
              </div>
            </div>
          </motion.div>
        </div>
      );
    }

    return <>{this.props.children}</>;
  }
}
