import React from 'react';

export class ErrorBoundary extends React.Component<{ onError?: (error, info) => void; FallbackComponent: any }> {
  // capture error
  static getDerivedStateFromError(error) {
    return { error };
  }

  state = { error: null };

  componentDidCatch(error, info) {
    console.error('组件边界错误', error);
    this.props.onError?.(error, info);
  }

  render() {
    const { error } = this.state;
    // @ts-expect-error ts(2339) (at least one of these will be defined though, and we check for their existence)
    const { fallbackRender, FallbackComponent, fallback } = this.props;

    if (error !== null) {
      const props = {
        error,
      };

      if (React.isValidElement(fallback)) {
        return fallback;
      }
      if (typeof fallbackRender === 'function') {
        return fallbackRender(props);
      }
      if (FallbackComponent) {
        return <FallbackComponent {...props} />;
      }
      return `Error Render: ${error?.message}`;
    }

    return this.props.children;
  }
}

export function createErrorFallback(cmpKey: string, id: string) {
  return function ComponentErrorFallback(props: any) {
    let isComponentError = true;
    let tipsContent = '组件错误';
    return (
      <div
        className={`component-error-box`}
        style={{
          width: 169,
          height: 91,
          background: 'rgb(241, 242, 245)',
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          margin: '6px',
        }}
        title={
          isComponentError
            ? `组件${cmpKey} ${id}发生了错误，请确保您使用正确的组件库或联系组件作者错误信息：${props.error}`
            : tipsContent
        }
      >
        <div
          className="component-error-box-icon"
          style={{
            height: 32,
            width: 32,
            backgroundSize: '100% 100%',
            backgroundRepeat: 'no-repeat',
            backgroundImage: 'url(https://imgcache.qq.com/qcloud/lowcode/static/ide/component-fail.svg)',
          }}
        />
      </div>
    );
  };
}

export function ComponentNotFound({ module = '', component }) {
  return (
    <div style={{ color: 'red' }}>
      组件<em>{`${module}:${component}`}</em>未找到
    </div>
  );
}
