"use client"

import { Component, type ReactNode } from "react"
import { AlertCircle } from "lucide-react"

import { EmptyState } from "@/shared/components/ui/empty-state"
import { useTranslations } from "next-intl"

interface SettingsSectionErrorBoundaryProps {
  children: ReactNode
}

interface SettingsSectionErrorBoundaryState {
  hasError: boolean
}

/**
 * 设置页分区 Error Boundary
 *
 * 包裹每个 TabsContent 内部组件，避免单个区块崩溃导致整页不可用。
 */
export class SettingsSectionErrorBoundary extends Component<
  SettingsSectionErrorBoundaryProps,
  SettingsSectionErrorBoundaryState
> {
  state: SettingsSectionErrorBoundaryState = { hasError: false }

  static getDerivedStateFromError(): SettingsSectionErrorBoundaryState {
    return { hasError: true }
  }

  handleRetry = (): void => {
    this.setState({ hasError: false })
  }

  render(): ReactNode {
    if (this.state.hasError) {
      return (
        <SettingsSectionErrorFallback onRetry={this.handleRetry} />
      )
    }
    return this.props.children
  }
}

function SettingsSectionErrorFallback({
  onRetry,
}: {
  onRetry: () => void
}): ReactNode {
  const t = useTranslations("settings.errors")
  return (
    <EmptyState
      icon={AlertCircle}
      title={t("sectionLoadFailed")}
      description={t("sectionLoadFailedDesc")}
      action={{
        label: t("retry"),
        onClick: onRetry,
      }}
      className="border-none shadow-none h-auto"
    />
  )
}
