'use client';

import { ErrorBoundary as ReactErrorBoundary } from 'react-error-boundary';
import { AlertCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';

interface ErrorFallbackProps {
  error: Error;
  resetErrorBoundary: () => void;
}

function ErrorFallback({ error, resetErrorBoundary }: ErrorFallbackProps) {
  return (
    <div className="flex min-h-[400px] flex-col items-center justify-center p-4">
      <AlertCircle className="h-16 w-16 text-destructive mb-4" />
      <h2 className="text-2xl font-bold mb-2">Something went wrong</h2>
      <p className="text-muted-foreground mb-4 text-center max-w-md">
        {error.message || 'An unexpected error occurred'}
      </p>
      <div className="flex gap-2">
        <Button onClick={resetErrorBoundary}>
          Try again
        </Button>
        <Button
          variant="outline"
          onClick={() => window.location.href = '/'}
        >
          Go to Dashboard
        </Button>
      </div>
    </div>
  );
}

interface ErrorBoundaryProps {
  children: React.ReactNode;
}

export function ErrorBoundary({ children }: ErrorBoundaryProps) {
  return (
    <ReactErrorBoundary
      FallbackComponent={ErrorFallback}
      onReset={() => {
        // Optional: Reset application state here
        // For now, we'll just reload the current page
        window.location.reload();
      }}
      onError={(error, errorInfo) => {
        // Log error to console in development
        console.error('Error caught by boundary:', error, errorInfo);

        // In production, you could send this to an error tracking service
        // like Sentry, LogRocket, etc.
      }}
    >
      {children}
    </ReactErrorBoundary>
  );
}
