'use client';

import { Component, ErrorInfo, ReactNode } from 'react';
import { useRouter } from 'next/navigation';

interface Props {
    children: ReactNode;
    fallback?: ReactNode;
}

interface State {
    hasError: boolean;
    error?: Error;
}

export class ErrorBoundary extends Component<Props, State> {
    public state: State = {
        hasError: false
    };

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

    public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
        console.error('Uncaught error:', error, errorInfo);
    }

    private handleReset = () => {
        // Clear auth token and reload
        document.cookie = 'authToken=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
        window.location.href = '/';
    };

    public render() {
        if (this.state.hasError) {
            return (
                <div className="flex items-center justify-center min-h-screen p-4">
                    <div className="text-center max-w-md">
                        <h2 className="text-2xl font-bold mb-4">
                            {this.state.error?.message === 'Session expired' ? 'Session Expired' : 'Something went wrong'}
                        </h2>
                        <p className="mb-6 text-gray-600 dark:text-gray-300">
                            {this.state.error?.message === 'Session expired' 
                                ? 'Your session has expired. Please log in again.'
                                : 'An unexpected error occurred. Please try again.'}
                        </p>
                        <button
                            onClick={this.handleReset}
                            className="px-6 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors"
                        >
                            Return to Home
                        </button>
                    </div>
                </div>
            );
        }

        return this.props.children;
    }
}

export default ErrorBoundary;
