import React from 'react';
import { Box, Button, Container, Paper, Typography } from '@mui/material';
import ErrorOutlineIcon from '@mui/icons-material/ErrorOutline';
import RefreshIcon from '@mui/icons-material/Refresh';
import { useTranslation } from 'react-i18next';

/**
 * Error Boundary Component
 * Catches JavaScript errors anywhere in the child component tree
 * Prevents application crashes and displays user-friendly error messages
 * 
 * Security: Does NOT expose stack traces or technical details to users
 */
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      hasError: false,
      errorCount: 0
    };
  }

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // Log error details (only in development)
    if (process.env.NODE_ENV !== 'production') {
      console.error('Error Boundary caught an error:', error, errorInfo);
    }
    
    // Update error count
    this.setState(prevState => ({
      errorCount: prevState.errorCount + 1
    }));
    
    // You can log to an error reporting service here
    // logErrorToService(error, errorInfo);
  }

  handleReset = () => {
    this.setState({
      hasError: false,
      errorCount: 0
    });
  };

  handleReload = () => {
    window.location.reload();
  };

  render() {
    if (this.state.hasError) {
      return <ErrorFallback onReset={this.handleReset} onReload={this.handleReload} />;
    }

    return this.props.children;
  }
}

/**
 * Error Fallback Component
 * Displays a user-friendly error message with recovery options
 */
function ErrorFallback({ onReset, onReload }) {
  const { t } = useTranslation();

  return (
    <Container maxWidth="sm" sx={{ mt: 8 }}>
      <Paper elevation={3} sx={{ p: 4, textAlign: 'center' }}>
        <ErrorOutlineIcon 
          sx={{ 
            fontSize: 80, 
            color: 'error.main',
            mb: 2 
          }} 
        />
        
        <Typography variant="h4" gutterBottom color="error">
          {t('errors.general.unexpected')}
        </Typography>
        
        <Typography variant="body1" color="text.secondary" sx={{ mb: 3 }}>
          {t('errors.general.tryAgain')}
        </Typography>
        
        <Box sx={{ display: 'flex', gap: 2, justifyContent: 'center', flexWrap: 'wrap' }}>
          <Button
            variant="contained"
            startIcon={<RefreshIcon />}
            onClick={onReset}
            color="primary"
          >
            {t('errors.general.tryAgain')}
          </Button>
          
          <Button
            variant="outlined"
            onClick={onReload}
            color="primary"
          >
            {t('refresh')}
          </Button>
        </Box>
        
        <Typography 
          variant="caption" 
          display="block" 
          sx={{ mt: 3 }}
          color="text.secondary"
        >
          {t('errors.general.contactSupport')}
        </Typography>
      </Paper>
    </Container>
  );
}

export default ErrorBoundary;
