'use client';

import React, { Component, ReactNode } from 'react';
import { AlertTriangle, RefreshCw, ArrowLeft, Home } from 'lucide-react';
import Link from 'next/link';

interface Props {
  serviceName: string;
  fallbackUrl?: string;
  children: ReactNode;
}

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

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

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

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    console.error(`[MFE Error Boundary] Error in ${this.props.serviceName}:`, error, errorInfo);
  }

  handleRetry = () => {
    this.setState({ hasError: false, error: undefined });
    window.location.reload();
  };

  render() {
    if (this.state.hasError) {
      return (
        <div className="min-h-[60vh] flex items-center justify-center p-6">
          <div className="max-w-md w-full rounded-2xl border border-white/10 bg-slate-900/90 p-8 text-center shadow-2xl backdrop-blur-xl">
            <div className="mx-auto flex h-16 w-16 items-center justify-center rounded-2xl bg-red-500/10 text-red-400 mb-6 border border-red-500/20">
              <AlertTriangle className="h-8 w-8" />
            </div>
            
            <h3 className="text-xl font-bold text-white mb-2">
              {this.props.serviceName} Temporarily Unavailable
            </h3>
            
            <p className="text-sm text-gray-400 mb-6 leading-relaxed">
              We encountered an issue loading this service. The rest of the platform remains fully functional.
            </p>

            <div className="flex flex-col gap-3">
              <button
                onClick={this.handleRetry}
                className="flex items-center justify-center gap-2 w-full rounded-xl bg-gradient-to-r from-indigo-500 to-purple-600 px-4 py-3 text-sm font-semibold text-white shadow-lg shadow-indigo-500/25 hover:opacity-95 transition"
              >
                <RefreshCw className="h-4 w-4" />
                Retry Loading Service
              </button>

              <Link
                href="/services"
                className="flex items-center justify-center gap-2 w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-sm font-medium text-gray-300 hover:bg-white/10 hover:text-white transition"
              >
                <ArrowLeft className="h-4 w-4" />
                Return to All Services
              </Link>
            </div>
          </div>
        </div>
      );
    }

    return this.props.children;
  }
}
