import Button from '@/components/ui/Button.tsx';
import IconWrapper from '@/components/ui/IconWrapper.tsx';
import { useTranslation } from '@/hooks/useI18n';
import { XCircle } from 'lucide-react';
import { Component, ErrorInfo, ReactNode } from 'react';

interface Props {
  children?: ReactNode;
}

interface ErrorState {
  hasError: boolean;
  error?: Error;
}

const ErrorFallback = ({ error, onRefresh }: { error?: Error; onRefresh: () => void }) => {
  const { t } = useTranslation();

  return (
    <div className="flex flex-col items-center justify-center min-h-screen bg-background p-8 text-center">
      <IconWrapper className="bg-destructive/10 text-destructive">
        <XCircle className="h-8 w-8 text-current" />
      </IconWrapper>
      <h1 className="font-serif text-3xl font-bold text-destructive">
        {t('error.somethingWentWrong')}
      </h1>
      <p className="mt-4 text-lg text-muted-foreground">{t('error.tryRefreshing')}</p>
      <pre className="mt-4 text-sm text-left bg-muted p-4 rounded-md max-w-full overflow-auto">
        {error?.message || t('error.unknownError')}
      </pre>
      <Button onClick={onRefresh} className="mt-6">
        {t('error.refreshPage')}
      </Button>
    </div>
  );
};

class ErrorBoundary extends Component<Props, ErrorState> {
  state: ErrorState = {
    hasError: false,
    error: undefined,
  };

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

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error('Uncaught error:', error, errorInfo);
  }

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

  render() {
    if (this.state.hasError) {
      return <ErrorFallback error={this.state.error} onRefresh={this.handleRefresh} />;
    }

    return this.props.children;
  }
}

export default ErrorBoundary;
