"use client";

import { Component, type ReactNode, type ErrorInfo } from "react";
import { Button } from "@/shared/components/ui/button";

interface Props {
  children: ReactNode;
  fallback?: ReactNode;
  /** 错误时的回调，用于上报埋点 */
  onError?: (error: Error, info: ErrorInfo) => void;
}

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

/**
 * 备课模块错误边界。
 * 包裹独立数据区块（版本抽屉/题库选择器/知识点选择器/发布对话框），
 * 单个区块异常不影响整页。
 */
export class LessonPlanErrorBoundary 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, info: ErrorInfo): void {
    if (this.props.onError) {
      this.props.onError(error, info);
    }
  }

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

  render(): ReactNode {
    if (this.state.hasError) {
      if (this.props.fallback) return this.props.fallback;
      return (
        <div className="flex flex-col items-center justify-center p-8 gap-3 text-center">
          <p className="text-sm text-on-surface-variant">
            {this.state.error?.message ?? "区块加载失败"}
          </p>
          <Button variant="outline" size="sm" onClick={this.handleRetry}>
            重试
          </Button>
        </div>
      );
    }
    return this.props.children;
  }
}
