import React, { Component, ErrorInfo, ReactNode } from 'react';
import { AlertTriangle } from 'lucide-react';

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

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

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, info: ErrorInfo) {
    console.error('ErrorBoundary caught:', error, info);
  }

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

  render() {
    if (this.state.hasError) {
      if (this.props.fallback) return this.props.fallback;
      return (
        <div className="flex flex-col items-center justify-center py-16 text-center px-4">
          <AlertTriangle className="w-16 h-16 text-[var(--danger)] mb-4" />
          <h3 className="text-2xl font-display font-semibold text-[var(--ink)] mb-2">Something went wrong</h3>
          <p className="text-[var(--ink-muted)] max-w-md mb-2">
            A component failed to render. This incident has been logged.
          </p>
          {this.state.error && (
            <details className="mb-4 text-left max-w-md">
              <summary className="text-sm text-[var(--ink-muted)] cursor-pointer">Technical details</summary>
              <pre className="mt-2 text-xs bg-[var(--surface-2)] p-3 rounded-[var(--r)] overflow-auto">
              {this.state.error.message}
              </pre>
            </details>
          )}
          <button
            onClick={this.handleRetry}
            className="px-6 py-2 bg-[var(--brand-500)] text-[var(--ink-inverse)] rounded-[var(--r)] hover:bg-[var(--brand-600)] transition"
          >
            Try Again
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}