/**
 * RequestDetail Router Component
 * 
 * Purpose: Routes to the appropriate flow-specific RequestDetail screen
 * 
 * Architecture:
 * - This is a router that determines the flow type and renders the appropriate screen
 * - Each flow has its own complete RequestDetail screen in its folder
 * - Deleting a flow folder removes all related code (truly modular)
 * 
 * IMPORTANT: This file only routes. All actual implementation is in flow-specific folders.
 * Deleting src/custom/ or src/dealer-claim/ removes ALL related code.
 */

import { Component, ErrorInfo, ReactNode } from 'react';
import { useParams } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { AlertTriangle, RefreshCw } from 'lucide-react';
import { useRequestDetails } from '@/hooks/useRequestDetails';
import { useAuth } from '@/contexts/AuthContext';
import { getRequestFlowType } from '@/utils/requestTypeUtils';
import { getRequestDetailScreen } from '@/flows';
import { RequestDetailProps } from './types/requestDetail.types';

/**
 * Error Boundary Component
 */
class RequestDetailErrorBoundary extends Component<{ children: ReactNode }, { hasError: boolean; error: Error | null }> {
  constructor(props: { children: ReactNode }) {
    super(props);
    this.state = { hasError: false, error: null };
  }

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

  override componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error('RequestDetail Router Error:', error, errorInfo);
  }

  override render() {
    if (this.state.hasError) {
      return (
        <div className="min-h-screen bg-gray-50 flex items-center justify-center p-6">
          <div className="max-w-md w-full bg-white rounded-lg shadow-lg p-8 text-center">
            <AlertTriangle className="w-16 h-16 text-red-500 mx-auto mb-4" />
            <h2 className="text-2xl font-bold mb-2">Error Loading Request</h2>
            <p className="text-gray-600 mb-4">{this.state.error?.message || 'An unexpected error occurred'}</p>
            <Button onClick={() => window.location.reload()} className="mr-2">
              Reload Page
            </Button>
            <Button variant="outline" onClick={() => window.history.back()}>
              Go Back
            </Button>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}

/**
 * RequestDetailRouter Component
 * 
 * Routes to the appropriate flow-specific RequestDetail screen based on request type.
 * This ensures complete modularity - deleting a flow folder removes all related code.
 */
function RequestDetailRouter({ requestId: propRequestId, onBack, dynamicRequests = [] }: RequestDetailProps) {
  const params = useParams<{ requestId: string }>();
  const requestIdentifier = params.requestId || propRequestId || '';
  const { user } = useAuth();

  // Fetch request details to determine flow type
  const {
    apiRequest,
    loading: requestLoading,
  } = useRequestDetails(requestIdentifier, dynamicRequests, user);

  // Loading state while determining flow type
  if (requestLoading && !apiRequest) {
    return (
      <div className="flex items-center justify-center h-screen bg-gray-50" data-testid="loading-state">
        <div className="text-center">
          <RefreshCw className="w-12 h-12 text-blue-600 animate-spin mx-auto mb-4" />
          <p className="text-gray-600">Loading request details...</p>
        </div>
      </div>
    );
  }

  // Determine flow type and get the appropriate RequestDetail screen
  const flowType = getRequestFlowType(apiRequest);
  const RequestDetailScreen = getRequestDetailScreen(flowType);

  // Render the flow-specific RequestDetail screen
  // Each flow has its own complete implementation in its folder
  return (
    <RequestDetailScreen
      requestId={propRequestId}
      onBack={onBack}
      dynamicRequests={dynamicRequests}
    />
  );
}

/**
 * RequestDetail Component (Exported)
 * 
 * This is now a router that delegates to flow-specific RequestDetail screens.
 * Each flow has its own complete RequestDetail implementation in its folder.
 * 
 * To remove a flow type completely:
 * 1. Delete the flow folder (e.g., src/dealer-claim/)
 * 2. Remove it from src/flows.ts FlowRegistry
 * 3. That's it! All related code is gone.
 */
export function RequestDetail(props: RequestDetailProps) {
  return (
    <RequestDetailErrorBoundary>
      <RequestDetailRouter {...props} />
    </RequestDetailErrorBoundary>
  );
}
