import { Component } from 'react';
import type { ErrorInfo, ReactNode } from 'react';
import { Result, Button, Space, Alert } from 'antd';
import { ReloadOutlined, RollbackOutlined } from '@ant-design/icons';

interface Props {
  children: ReactNode;
}

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

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

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

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error('ErrorBoundary caught an error:', error, errorInfo);
  }

  handleReload = () => {
    // Clear all potentially corrupted storage
    try {
      // Clear wagmi
      localStorage.removeItem('wagmi.store');
      localStorage.removeItem('wagmi.connected');
      localStorage.removeItem('wagmi.wallet');
      // Clear WalletConnect
      const keysToRemove: string[] = [];
      for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i);
        if (
          key &&
          (key.startsWith('wc@') ||
            key.startsWith('wagmi') ||
            key.startsWith('@w3m') ||
            key.includes('walletconnect') ||
            key === 'yt_asset_tx_history')
        ) {
          keysToRemove.push(key);
        }
      }
      keysToRemove.forEach((key) => localStorage.removeItem(key));
      sessionStorage.clear();
    } catch (e) {
      console.error('Failed to clear storage:', e);
    }
    window.location.reload();
  };

  handleReset = () => {
    this.setState({ hasError: false, error: null });
  };

  render() {
    if (this.state.hasError) {
      return (
        <div style={{ padding: '50px', height: '100vh', background: '#f0f2f5' }}>
          <Result
            status="error"
            title="Something went wrong"
            subTitle={
              typeof this.state.error?.message === 'string'
                ? this.state.error.message
                : JSON.stringify(this.state.error?.message) || 'Unknown error'
            }
            extra={
              <>
                <Alert
                  message="常见原因"
                  description={
                    <ul style={{ paddingLeft: 20 }}>
                      <li>多个钱包插件冲突</li>
                      <li>网络连接问题</li>
                      <li>钱包状态损坏</li>
                    </ul>
                  }
                  type="info"
                  style={{ marginBottom: 24, textAlign: 'left' }}
                />
                <Space>
                  <Button icon={<RollbackOutlined />} onClick={this.handleReset}>
                    重试
                  </Button>
                  <Button type="primary" icon={<ReloadOutlined />} onClick={this.handleReload}>
                    清除缓存并刷新
                  </Button>
                </Space>
                <Alert
                  message="提示：如果问题持续存在，请尝试禁用其他钱包插件，只保留一个。"
                  type="warning"
                  showIcon
                  style={{ marginTop: 24 }}
                />
              </>
            }
          />
        </div>
      );
    }

    return this.props.children;
  }
}
