import React, { Component, ErrorInfo, ReactNode } from 'react';
import { Heading, Text, Button, Center, VStack } from '@chakra-ui/react';
import i18next from 'i18next';

interface ErrorBoundaryState {
  hasError: boolean;
  error: Error | null;
  errorInfo: ErrorInfo | null;
}

interface ErrorBoundaryProps {
  children: ReactNode;
}

class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
  constructor(props: ErrorBoundaryProps) {
    super(props);
    this.state = {
      hasError: false,
      error: null,
      errorInfo: null,
    };
  }

  static getDerivedStateFromError(): Partial<ErrorBoundaryState> {
    return { hasError: true };
  }

  componentDidCatch(error: Error, errorInfo: ErrorInfo): void {
    console.error('Error caught by ErrorBoundary:', error, errorInfo);
    this.setState({ error, errorInfo });
  }

  render() {
    const { hasError } = this.state;
    //TODO: добавить анимацию после залива 404 страницы
    if (hasError) {
      return (
        <Center minH='100vh'>
          <VStack spacing={4} textAlign='center'>
            <Heading as='h1' size='2xl'>
              {i18next.t('dry-wash.errorBoundary.title')}
            </Heading>
            <Text fontSize='lg'>
              {i18next.t('dry-wash.errorBoundary.description')}
            </Text>
            <Button
              colorScheme='teal'
              size='lg'
              variant='outline'
              onClick={() => window.location.reload()}
            >
              {i18next.t('dry-wash.errorBoundary.button.reload')}
            </Button>
          </VStack>
        </Center>
      );
    }

    return this.props.children;
  }
}

export default ErrorBoundary;
