import KFEmpty, { EmptyType } from '@/components/KFEmpty';
import { Button } from 'antd';
import { Component, ReactNode } from 'react';

interface ErrorBoundaryProps {
  children: ReactNode;
  fallback?: ReactNode; // Optional fallback UI to show in case of error
}

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

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

  static getDerivedStateFromError(error: Error): ErrorBoundaryState {
    // Update state so the next render shows the fallback UI
    return { hasError: true, error };
  }

  // componentDidCatch(error: Error, errorInfo: ErrorInfo) {
  //   // You can log the error to an error reporting service here
  //   console.error('Error caught by ErrorBoundary:', error.message, errorInfo.componentStack);
  // }

  render() {
    if (this.state.hasError) {
      return this.props.fallback || <ErrorBoundaryFallback error={this.state.error} />;
    }
    return this.props.children;
  }
}

function ErrorBoundaryFallback({ error }: { error: Error | null }) {
  const message = error && error instanceof Error ? error.message : 'Unknown error';
  const errorMsg =
    process.env.NODE_ENV === 'development' ? message : '非常抱歉，程序运行错误，\n我们会尽快修复。';
  return (
    <KFEmpty
      style={{ height: '100vh' }}
      type={EmptyType.NotFound}
      title="出错了"
      content={errorMsg}
      footer={() => {
        return (
          <>
            <Button
              type="default"
              onClick={() => {
                window.history.pushState({}, '', '/');
                window.location.reload();
              }}
            >
              返回首页
            </Button>
            <Button
              type="primary"
              style={{ marginLeft: 20 }}
              onClick={() => window.location.reload()}
            >
              刷新
            </Button>
          </>
        );
      }}
    ></KFEmpty>
  );
}

export default ErrorBoundary;
