import { Component, ErrorInfo, ReactNode } from 'react';
import { AlertTriangle, RefreshCw } from 'lucide-react';
import { Button } from './ui/Button';

interface Props {
  children: ReactNode;
}

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

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

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

  public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error('Uncaught error:', error, errorInfo);
  }

  public render() {
    if (this.state.hasError) {
      return (
        <div className="min-h-screen flex items-center justify-center bg-surface-50 px-4">
          <div className="max-w-md w-full text-center animate-fade-in">
            <div className="w-16 h-16 rounded-2xl bg-danger-50 flex items-center justify-center mx-auto mb-4">
              <AlertTriangle className="w-8 h-8 text-danger-500" />
            </div>
            <h1 className="text-xl font-bold text-surface-900 mb-2">Something went wrong</h1>
            <p className="text-sm text-surface-500 mb-6">
              We encountered an unexpected error. Try refreshing the page or going back to the dashboard.
            </p>
            {this.state.error && (
              <div className="bg-surface-100 rounded-lg p-3 mb-6 text-left">
                <code className="text-xs text-danger-600 break-all">{this.state.error.message}</code>
              </div>
            )}
            <div className="flex gap-3 justify-center">
              <Button
                variant="secondary"
                icon={<RefreshCw className="w-4 h-4" />}
                onClick={() => window.location.reload()}
              >
                Refresh page
              </Button>
              <Button onClick={() => window.location.href = '/'}>
                Go to Dashboard
              </Button>
            </div>
          </div>
        </div>
      );
    }

    return this.props.children;
  }
}
