"use client"

import React, { Component, ErrorInfo, ReactNode } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../ui/card"
import { Button } from "../ui/button"
import { AlertTriangle, RefreshCw, Lock, Sparkles } from "lucide-react"
import { cn } from "../../lib/utils"
import { useSubscription } from "../../hooks/use-subscription"

interface ErrorBoundaryProps {
  children: ReactNode
  fallback?: ReactNode
  className?: string
  onError?: (error: Error, errorInfo: ErrorInfo) => void
}

interface ErrorBoundaryState {
  hasError: boolean
  error?: Error
}

class ErrorBoundaryInternal extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
  constructor(props: ErrorBoundaryProps) {
    super(props)
    this.state = { hasError: false }
  }

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

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    this.props.onError?.(error, errorInfo)
    console.error('ErrorBoundary caught an error:', error, errorInfo)
  }

  render() {
    if (this.state.hasError) {
      if (this.props.fallback) {
        return this.props.fallback
      }

      return (
        <div className={cn("flex items-center justify-center min-h-[200px] p-4", this.props.className)}>
          <Card className="w-full max-w-md">
            <CardHeader className="text-center">
              <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-red-100">
                <AlertTriangle className="h-6 w-6 text-red-600" />
              </div>
              <CardTitle>Something went wrong</CardTitle>
              <CardDescription>
                An error occurred while rendering this component
              </CardDescription>
            </CardHeader>
            <CardContent className="text-center">
              <Button 
                onClick={() => this.setState({ hasError: false, error: undefined })}
                className="mt-4"
              >
                <RefreshCw className="mr-2 h-4 w-4" />
                Try again
              </Button>
            </CardContent>
          </Card>
        </div>
      )
    }

    return this.props.children
  }
}

function ErrorBoundaryWrapper(props: ErrorBoundaryProps) {
  // Check if we're in docs mode or have pro access
  const { hasProAccess, isLoading } = useSubscription()
  
  // In docs mode, always show the component
  
  // If not in docs mode and no pro access, show upgrade prompt
  if (!isLoading && !hasProAccess) {
    return (
      <Card className={cn("w-fit", props.className)}>
        <CardContent className="py-6 text-center">
          <div className="space-y-4">
            <div className="rounded-full bg-purple-100 dark:bg-purple-900/30 p-3 w-fit mx-auto">
              <Lock className="h-6 w-6 text-purple-600 dark:text-purple-400" />
            </div>
            <div>
              <h3 className="font-semibold text-sm mb-2">Pro Feature</h3>
              <p className="text-muted-foreground text-xs mb-4">
                Error Boundary is available exclusively to MoonUI Pro subscribers.
              </p>
              <a href="/pricing">
                <Button size="sm">
                  <Sparkles className="mr-2 h-4 w-4" />
                  Upgrade to Pro
                </Button>
              </a>
            </div>
          </div>
        </CardContent>
      </Card>
    )
  }

  return <ErrorBoundaryInternal {...props} />
}

export const ErrorBoundary = ErrorBoundaryWrapper