"use client"

import { Component, type ErrorInfo, type JSX, type ReactNode } from "react"
import { AlertCircle } from "lucide-react"
import { useRouter } from "next/navigation"
import { useTranslations } from "next-intl"

import { Button } from "@/shared/components/ui/button"

interface SchoolErrorBoundaryProps {
  children: ReactNode
  fallback?: ReactNode
}

interface SchoolErrorBoundaryState {
  hasError: boolean
}

function SchoolErrorFallback({ onReset }: { onReset: () => void }): JSX.Element {
  const t = useTranslations("school")
  const router = useRouter()

  const handleRetry = (): void => {
    onReset()
    router.refresh()
  }

  return (
    <div
      role="alert"
      className="flex min-h-[400px] flex-col items-center justify-center rounded-md border border-dashed p-8 text-center"
    >
      <div className="flex h-16 w-16 items-center justify-center rounded-full bg-destructive/10">
        <AlertCircle className="h-8 w-8 text-destructive" />
      </div>
      <h3 className="mt-4 text-lg font-semibold">{t("errors.boundary.title")}</h3>
      <p className="mb-4 mt-2 max-w-md text-sm text-muted-foreground">
        {t("errors.boundary.description")}
      </p>
      <Button onClick={handleRetry}>{t("errors.boundary.retry")}</Button>
    </div>
  )
}

export class SchoolErrorBoundary extends Component<
  SchoolErrorBoundaryProps,
  SchoolErrorBoundaryState
> {
  constructor(props: SchoolErrorBoundaryProps) {
    super(props)
    this.state = { hasError: false }
  }

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

  componentDidCatch(error: Error, errorInfo: ErrorInfo): void {
    console.error("SchoolErrorBoundary caught an error:", error, errorInfo)
  }

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

  render(): ReactNode {
    if (this.state.hasError) {
      return this.props.fallback ?? <SchoolErrorFallback onReset={this.handleReset} />
    }
    return this.props.children
  }
}
