import { Component, type ReactNode } from 'react'
import { Box, Button, Typography } from '@mui/material'
import { AlertTriangle } from 'lucide-react'

interface Props {
  children: ReactNode
  fallback?: ReactNode
}

interface State {
  hasError: boolean
  error?: Error
}

export class AppErrorBoundary extends Component<Props, State> {
  constructor(props: Props) {
    super(props)
    this.state = { hasError: false }
  }

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

  handleReset = () => {
    this.setState({ hasError: false, error: undefined })
  }

  render() {
    if (this.state.hasError) {
      if (this.props.fallback) return this.props.fallback
      return (
        <Box className="flex flex-col items-center justify-center min-h-64 gap-4 p-8 text-center">
          <AlertTriangle size={40} className="text-red-500" />
          <Typography variant="h6" color="error">Unerwarteter Fehler</Typography>
          <Typography variant="body2" color="text.secondary" className="max-w-md">
            {this.state.error?.message ?? 'Ein unbekannter Fehler ist aufgetreten.'}
          </Typography>
          <Button variant="outlined" onClick={this.handleReset}>Neu laden</Button>
        </Box>
      )
    }
    return this.props.children
  }
}
