'use client'

import React from 'react'
import { AlertTriangle, RefreshCw } from 'lucide-react'
import { Button } from '@/components/ui/button'

interface Props {
  children: React.ReactNode
  fallbackTitle?: string
  fallbackDesc?: string
}

interface State {
  hasError: boolean
  error?: Error
}

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

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

  componentDidCatch(error: Error, info: React.ErrorInfo) {
    console.error('[ErrorBoundary]', error, info.componentStack)
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="flex flex-col items-center justify-center bg-gray-50 border border-dashed border-gray-300 rounded-2xl p-10 text-center min-h-[200px]">
          <AlertTriangle className="w-10 h-10 text-amber-400 mb-3" />
          <h3 className="font-bold text-gray-800 mb-1">
            {this.props.fallbackTitle ?? 'تعذّر تحميل هذا القسم'}
          </h3>
          <p className="text-sm text-gray-500 mb-4 max-w-xs">
            {this.props.fallbackDesc ?? 'حدث خطأ غير متوقع. حاول إعادة تحميل الصفحة.'}
          </p>
          <Button
            size="sm"
            variant="outline"
            onClick={() => this.setState({ hasError: false })}
            className="gap-2"
          >
            <RefreshCw className="w-4 h-4" />
            إعادة المحاولة
          </Button>
        </div>
      )
    }
    return this.props.children
  }
}

// ── Functional wrapper for server-component pages ─────────────────
export function withErrorBoundary<P extends object>(
  Component: React.ComponentType<P>,
  fallbackTitle?: string
) {
  return function WrappedComponent(props: P) {
    return (
      <ErrorBoundary fallbackTitle={fallbackTitle}>
        <Component {...props} />
      </ErrorBoundary>
    )
  }
}
