"use client";

import React from "react";
import { AlertTriangle } from "lucide-react";

interface ErrorBoundaryProps {
  children: React.ReactNode;
}

interface ErrorBoundaryState {
  hasError: boolean;
  error: Error | null;
}

export class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
  constructor(props: ErrorBoundaryProps) {
    super(props);
    this.state = { hasError: false, error: null };
  }

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

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    console.error("ErrorBoundary caught an error:", error, errorInfo);
  }

  handleReset = () => {
    this.setState({ hasError: false, error: null });
  };

  render() {
    if (this.state.hasError) {
      return (
        <div className="flex min-h-[50vh] items-center justify-center px-4">
          <div className="w-full max-w-md rounded-lg bg-white p-8 shadow-lg border border-gray-200 text-center">
            <AlertTriangle className="mx-auto h-12 w-12 text-amber-500 mb-4" />

            <h2 className="text-xl font-bold text-gray-900 mb-2">
              कुछ गलत हो गया / Something went wrong
            </h2>

            <p className="text-sm text-gray-600 mb-6">
              एक अप्रत्याशित त्रुटि हुई है। कृपया पुनः प्रयास करें।
              <br />
              An unexpected error occurred. Please try again.
            </p>

            {this.state.error && (
              <p className="mb-6 rounded bg-red-50 p-3 text-xs text-red-600 text-left break-words">
                {this.state.error.message}
              </p>
            )}

            <button
              onClick={this.handleReset}
              className="inline-flex items-center gap-2 rounded-md bg-indigo-600 px-5 py-2.5 text-sm font-medium text-white hover:bg-indigo-700 transition-colors"
            >
              पुनः प्रयास करें / Try Again
            </button>
          </div>
        </div>
      );
    }

    return this.props.children;
  }
}
