import { Component } from 'react';
import type { ReactNode, ErrorInfo } from 'react';
import { Center, Paper, Title, Text, Button } from '@mantine/core';

interface Props {
  children: ReactNode;
}

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

export class ErrorBoundary extends Component<Props, State> {
  state: 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);
  }

  render() {
    if (this.state.hasError) {
      return (
        <Center h="100vh">
          <Paper p="xl" shadow="md" radius="md" w={400}>
            <Title order={3} mb="sm">Something went wrong</Title>
            <Text c="dimmed" size="sm" mb="lg">
              {this.state.error?.message || 'An unexpected error occurred.'}
            </Text>
            <Button
              fullWidth
              onClick={() => {
                this.setState({ hasError: false, error: null });
                window.location.href = '/';
              }}
            >
              Reload page
            </Button>
          </Paper>
        </Center>
      );
    }

    return this.props.children;
  }
}
