/**
 * Dealer Claim Request Workflow Tab
 * 
 * This component is specific to Dealer Claim requests.
 * Located in: src/dealer-claim/components/request-detail/
 */

import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
import { TrendingUp, Clock, CheckCircle, CheckCircle2, CircleCheckBig, Upload, Mail, Download, Receipt, Activity, AlertTriangle, AlertOctagon, XCircle, History, ChevronDown, ChevronUp, RefreshCw, RotateCw, Eye, FileSpreadsheet, X, Loader2 } from 'lucide-react';
import { formatDateTime, formatDateDDMMYYYY } from '@/utils/dateFormatter';
import { formatHoursMinutes } from '@/utils/slaTracker';
import {
  AdditionalApproverReviewModal,
  DealerProposalSubmissionModal,
  InitiatorProposalApprovalModal,
  DeptLeadIOApprovalModal,
  DealerCompletionDocumentsModal,
  CreditNoteSAPModal,
  EmailNotificationTemplateModal,
  DMSPushModal,
  SnapshotDetailsModal
  // InitiatorActionModal - Removed, using direct buttons instead
} from './modals';
import { toast } from 'sonner';
import { submitProposal, updateIODetails, submitCompletion, updateEInvoice, sendCreditNoteToDealer, retriggerWFMPush } from '@/services/dealerClaimApi';
import { getWorkflowDetails, approveLevel, rejectLevel, handleInitiatorAction, getWorkflowHistory } from '@/services/workflowApi';
import { uploadDocument } from '@/services/documentApi';
import { TokenManager } from '@/utils/tokenManager';

interface DealerClaimWorkflowTabProps {
  request: any;
  user: any;
  isInitiator: boolean;
  onSkipApprover?: (data: any) => void;
  onRefresh?: () => void;
  documentPolicy: {
    maxFileSizeMB: number;
    allowedFileTypes: string[];
  };
  isSpectator?: boolean;
}

interface WorkflowStep {
  step: number;
  title: string;
  approver: string;
  description: string;
  tatHours: number;
  status: 'pending' | 'approved' | 'waiting' | 'rejected' | 'in_progress' | 'skipped';
  comment?: string;
  approvedAt?: string;
  elapsedHours?: number;
  // Special fields for dealer claims
  ioDetails?: {
    ioNumber: string;
    organizedBy: string;
    organizedAt: string;
    blockedAmount?: number;
    availableBalance?: number;
    remainingBalance?: number;
  };
  dmsDetails?: {
    dmsNumber: string;
    dmsRemarks: string;
    pushedBy: string;
    pushedAt: string;
  };
  einvoiceUrl?: string;
  emailTemplateUrl?: string;
  levelName?: string;
  versionHistory?: {
    current: any;
    previous: any;
    all?: any[];
  };
}

/**
 * Safe date formatter with fallback
 */
const formatDateSafe = (dateString: string | undefined | null): string => {
  if (!dateString) return '';
  try {
    return formatDateTime(dateString);
  } catch (error) {
    // Fallback to simple date format
    try {
      return new Date(dateString).toLocaleString('en-IN', {
        month: 'short',
        day: 'numeric',
        year: 'numeric',
        hour: 'numeric',
        minute: 'numeric',
        hour12: true,
      });
    } catch {
      return dateString;
    }
  }
};

/**
 * Get step icon based on status
 */
const getStepIcon = (status: string) => {
  switch (status) {
    case 'approved':
      return <CircleCheckBig className="w-5 h-5 text-green-600" />;
    case 'skipped':
      return <CheckCircle className="w-5 h-5 text-green-600" />;
    case 'pending':
      return <Clock className="w-5 h-5 text-blue-600" />;
    case 'rejected':
      return <CheckCircle className="w-5 h-5 text-red-600" />;
    default:
      return <Clock className="w-5 h-5 text-gray-400" />;
  }
};

/**
 * Get step badge variant
 */
const getStepBadgeVariant = (status: string) => {
  switch (status) {
    case 'approved':
      return 'bg-green-100 text-green-800 border-green-200';
    case 'skipped':
      return 'bg-green-50 text-green-700 border-green-200';
    case 'pending':
      return 'bg-purple-100 text-purple-800 border-purple-200';
    case 'rejected':
      return 'bg-red-100 text-red-800 border-red-200';
    default:
      return 'bg-gray-100 text-gray-800 border-gray-200';
  }
};

/**
 * Get step card styling
 */
const getStepCardStyle = (status: string, isActive: boolean) => {
  if (isActive && (status === 'pending' || status === 'in_progress')) {
    return 'border-purple-500 bg-purple-50 shadow-md';
  }
  if (status === 'approved' || status === 'skipped') {
    return 'border-green-500 bg-green-50';
  }
  if (status === 'rejected') {
    return 'border-red-500 bg-red-50';
  }
  return 'border-gray-200 bg-white';
};

/**
 * Get step icon background
 */
const getStepIconBg = (status: string) => {
  switch (status) {
    case 'approved':
      return 'bg-green-100';
    case 'skipped':
      return 'bg-green-100';
    case 'pending':
      return 'bg-purple-100';
    case 'rejected':
      return 'bg-red-100';
    default:
      return 'bg-gray-100';
  }
};

export function DealerClaimWorkflowTab({
  request,
  user,
  isInitiator,
  onSkipApprover: _onSkipApprover,
  onRefresh,
  documentPolicy,
  isSpectator = false
}: DealerClaimWorkflowTabProps) {
  const [showProposalModal, setShowProposalModal] = useState(false);
  const [showApprovalModal, setShowApprovalModal] = useState(false);
  const [showIOApprovalModal, setShowIOApprovalModal] = useState(false);
  const [showCompletionModal, setShowCompletionModal] = useState(false);
  const [showDMSPushModal, setShowDMSPushModal] = useState(false);
  const [showCreditNoteModal, setShowCreditNoteModal] = useState(false);
  const [showEmailTemplateModal, setShowEmailTemplateModal] = useState(false);
  const [selectedStepForEmail, setSelectedStepForEmail] = useState<{ stepNumber: number; stepName: string } | null>(null);
  const [showAdditionalApproverReviewModal, setShowAdditionalApproverReviewModal] = useState(false);
  const [selectedLevelForReview, setSelectedLevelForReview] = useState<{ levelId: string; levelName: string; approverName: string } | null>(null);
  // Removed - Initiator actions are now direct buttons in step card, no modal needed
  const [versionHistory, setVersionHistory] = useState<any[]>([]);
  const [showHistory, setShowHistory] = useState(false);
  const [expandedVersionSteps, setExpandedVersionSteps] = useState<Set<number>>(new Set());
  const [viewSnapshot, setViewSnapshot] = useState<{ data: any, type: 'PROPOSAL' | 'COMPLETION', title?: string } | null>(null);
  const [invoicePdfUrl, setInvoicePdfUrl] = useState<string | null>(null);
  const [showInvoicePdfModal, setShowInvoicePdfModal] = useState(false);
  const [invoicePdfLoading, setInvoicePdfLoading] = useState(false);

  // Load approval flows from real API
  const [approvalFlow, setApprovalFlow] = useState<any[]>([]);
  const [refreshTrigger, setRefreshTrigger] = useState(0);

  // Reload approval flows whenever request changes or after refresh
  // Always fetch from API to ensure fresh data (don't rely on cached request.approvalFlow)
  // Also watch for changes in totalLevels to detect when approvers are added
  useEffect(() => {
    const loadApprovalFlows = async () => {
      // Always load from real API to get the latest data
      if (request?.id || request?.requestId) {
        const requestId = request.id || request.requestId;
        try {
          const details = await getWorkflowDetails(requestId);
          const approvals = details?.approvalLevels || details?.approvals || [];
          if (approvals && approvals.length > 0) {
            // Transform approval levels to match expected format
            // Include levelName and levelNumber for proper mapping
            const flows = approvals
              .map((level: any) => ({
                step: level.levelNumber || level.level_number || 0,
                levelNumber: level.levelNumber || level.level_number || 0,
                levelName: level.levelName || level.level_name,
                approver: level.approverName || level.approver_name || '',
                approverEmail: (level.approverEmail || level.approver_email || '').toLowerCase(),
                status: level.status?.toLowerCase() || 'waiting',
                tatHours: level.tatHours || level.tat_hours || 24,
                elapsedHours: level.elapsedHours || level.elapsed_hours,
                approvedAt: level.actionDate || level.action_date,
                comment: level.comments || level.comment,
                levelId: level.levelId || level.level_id,
              }))
              // Sort by levelNumber to ensure correct order (critical for proper display)
              .sort((a: any, b: any) => (a.levelNumber || 0) - (b.levelNumber || 0));

            // Only update if the data actually changed (avoid unnecessary re-renders)
            setApprovalFlow(prevFlows => {
              // Check if flows are different
              if (prevFlows.length !== flows.length) {
                return flows;
              }
              // Check if any levelNumber, levelName, approverEmail, or status changed
              // Status change is critical - when an approval happens, status changes from 'in_progress' to 'approved'
              const hasChanges = prevFlows.some((prev: any, idx: number) => {
                const curr = flows[idx];
                return !curr ||
                  prev.levelNumber !== curr.levelNumber ||
                  prev.levelName !== curr.levelName ||
                  prev.approverEmail !== curr.approverEmail ||
                  prev.status !== curr.status; // Check status change
              });
              return hasChanges ? flows : prevFlows;
            });
          } else {
            // If no approvals found, clear the flow
            setApprovalFlow([]);
          }
        } catch (error) {
          console.warn('Failed to load approval flows from API:', error);
          // On error, try to use request.approvalFlow as fallback
          if (request?.approvalFlow && request.approvalFlow.length > 0) {
            setApprovalFlow(request.approvalFlow);
          }
        }
      } else if (request?.approvalFlow && request.approvalFlow.length > 0) {
        // Fallback: use request.approvalFlow only if no requestId available
        setApprovalFlow(request.approvalFlow);
      }
    };

    loadApprovalFlows();
  }, [request?.id, request?.requestId, request?.totalLevels, refreshTrigger]);

  // Also reload when request.currentStep or totalLevels changes (to catch step transitions and new approvers)
  useEffect(() => {
    if (request?.id || request?.requestId) {
      const requestId = request.id || request.requestId;
      const loadApprovalFlows = async () => {
        try {
          const details = await getWorkflowDetails(requestId);
          const approvals = details?.approvalLevels || details?.approvals || [];
          if (approvals && approvals.length > 0) {
            const flows = approvals
              .map((level: any) => ({
                step: level.levelNumber || level.level_number || 0,
                levelNumber: level.levelNumber || level.level_number || 0,
                levelName: level.levelName || level.level_name,
                approver: level.approverName || level.approver_name || '',
                approverEmail: (level.approverEmail || level.approver_email || '').toLowerCase(),
                status: level.status?.toLowerCase() || 'waiting',
                tatHours: level.tatHours || level.tat_hours || 24,
                elapsedHours: level.elapsedHours || level.elapsed_hours,
                approvedAt: level.actionDate || level.action_date,
                comment: level.comments || level.comment,
                levelId: level.levelId || level.level_id,
              }))
              // Sort by levelNumber to ensure correct order
              .sort((a: any, b: any) => (a.levelNumber || 0) - (b.levelNumber || 0));

            // Update state with new flows
            setApprovalFlow(flows);
          }
        } catch (error) {
          console.warn('Failed to load approval flows from API:', error);
        }
      };
      loadApprovalFlows();
    }
  }, [request?.currentStep, request?.totalLevels]);

  // Enhanced refresh handler that also reloads approval flows
  const handleRefresh = async () => {
    setRefreshTrigger(prev => prev + 1);
    // Small delay to ensure backend has fully processed the approval
    await new Promise(resolve => setTimeout(resolve, 500));
    onRefresh?.();
    loadVersionHistory();
  };

  const loadVersionHistory = async () => {
    if (request?.id || request?.requestId) {
      try {
        const history = await getWorkflowHistory(request.id || request.requestId);
        // Sort by createdAt descending to ensure most recent is at the top
        const sortedHistory = [...(history || [])].sort((a: any, b: any) => {
          return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
        });
        setVersionHistory(sortedHistory);
      } catch (error) {
        console.warn('Failed to load version history:', error);
      }
    }
  };

  useEffect(() => {
    loadVersionHistory();
  }, [request?.id, request?.requestId, refreshTrigger]);

  // Step title and description mapping based on actual step number (not array index)
  // This handles cases where approvers are added between steps
  const getStepTitle = (stepNumber: number, levelName?: string, approverName?: string): string => {
    // Check if this is a legacy workflow (8 steps) or new workflow (5 steps)
    // Legacy flows have system steps (Activity, E-Invoice, Credit Note) as approval levels
    const isLegacyFlow = (request?.totalLevels || 0) > 5 || (request?.approvalLevels?.length || 0) > 5;

    // Use levelName from backend if available (most accurate)
    // Check if it's an "Additional Approver" - this indicates a dynamically added approver
    if (levelName && levelName.trim()) {
      const levelNameLower = levelName.toLowerCase();

      // If it starts with "Additional Approver", use it as-is (it's already formatted)
      if (levelNameLower.includes('additional approver')) {
        return levelName;
      }

      // If levelName is NOT generic "Step X", return it
      // This fixes the issue where backend sends "Step 1" instead of "Dealer Proposal Submission"
      if (!/^step\s+\d+$/i.test(levelName)) {
        return levelName;
      }
    }

    // Fallback to mapping based on step number and flow version
    const stepTitleMap: Record<number, string> = isLegacyFlow
      ? {
        // Legacy 8-step flow
        1: 'Dealer - Proposal Submission',
        2: 'Requestor Evaluation & Confirmation',
        3: 'Department Lead Approval',
        4: 'Activity Creation',
        5: 'Dealer - Completion Documents',
        6: 'Requestor - Claim Approval',
        7: 'E-Invoice Generation',
        8: 'Credit Note from SAP',
      }
      : {
        // New 5-step flow
        1: 'Dealer - Proposal Submission',
        2: 'Requestor Evaluation & Confirmation',
        3: 'Department Lead Approval',
        4: 'Dealer - Completion Documents',
        5: 'Requestor - Claim Approval',
        6: 'E-Invoice Generation',
        7: 'Credit Note from SAP',
      };

    // If step number exists in map, use it
    if (stepTitleMap[stepNumber]) {
      return stepTitleMap[stepNumber];
    }

    // For dynamically added steps, create a title from approver name or generic
    if (approverName && approverName !== 'Unknown' && approverName !== 'System') {
      return `Additional Approver - ${approverName}`;
    }

    return `Additional Approver - Step ${stepNumber}`;
  };

  const getStepDescription = (stepNumber: number, levelName?: string, approverName?: string): string => {
    // Check if this is an "Additional Approver" (dynamically added)
    const isAdditionalApprover = levelName && levelName.toLowerCase().includes('additional approver');

    // If this is an additional approver, use generic description
    if (isAdditionalApprover) {
      if (approverName && approverName !== 'Unknown' && approverName !== 'System') {
        return `${approverName} will review and approve this request as an additional approver.`;
      }
      return `Additional approver will review and approve this request.`;
    }

    // Check if this is a legacy workflow (8 steps) or new workflow (5 steps)
    const isLegacyFlow = (request?.totalLevels || 0) > 5 || (request?.approvalLevels?.length || 0) > 5;

    // Use levelName to determine description (handles shifted steps correctly)
    // This ensures descriptions shift with their steps when approvers are added
    if (levelName && levelName.trim()) {
      const levelNameLower = levelName.toLowerCase();

      // Map level names to descriptions (works even after shifting)
      if (levelNameLower.includes('dealer') && levelNameLower.includes('proposal')) {
        return 'Dealer submits the proposal for the activity with comments including proposal document with requested details, cost break-up, timeline for closure, and other requests';
      }
      if (levelNameLower.includes('requestor') && (levelNameLower.includes('evaluation') || levelNameLower.includes('confirmation'))) {
        return 'Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)';
      }
      if (levelNameLower.includes('department lead')) {
        return 'Department Lead approval. Decision point: Approved? (YES → Budget is blocked in the respective IO for the activity / NO → More clarification required → Request is cancelled)';
      }
      // Re-added for legacy support
      if (levelNameLower.includes('activity creation')) {
        return 'Activity is created. Activity confirmation email is auto-triggered to dealer / requestor / Lead. IO confirmation to be made.';
      }
      if (levelNameLower.includes('dealer') && (levelNameLower.includes('completion') || levelNameLower.includes('documents'))) {
        return 'Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description';
      }
      if (levelNameLower.includes('requestor') && (levelNameLower.includes('claim') || levelNameLower.includes('approval'))) {
        return 'Requestor approves the claim in full or can modify the amount. If more information is required, can request additional details from dealer.';
      }
      if (levelNameLower.includes('e-invoice') || levelNameLower.includes('invoice generation') || levelNameLower.includes('dms')) {
        return 'E-Invoice will be generated upon settlement initiation.';
      }
      if (levelNameLower.includes('credit note') || levelNameLower.includes('sap')) {
        return 'Got credit note from SAP. Review and send to dealer to complete the claim management process.';
      }
    }

    // Fallback to step number mapping depending on flow version
    const stepDescriptionMap: Record<number, string> = isLegacyFlow
      ? {
        // Legacy 8-step flow
        1: 'Dealer submits the proposal for the activity with comments including proposal document with requested details, cost break-up, timeline for closure, and other requests',
        2: 'Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)',
        3: 'Department Lead approval. Decision point: Approved? (YES → Budget is blocked in the respective IO for the activity / NO → More clarification required → Request is cancelled)',
        4: 'Activity is created. Activity confirmation email is auto-triggered to dealer / requestor / Lead. IO confirmation to be made.',
        5: 'Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description',
        6: 'Requestor approves the claim in full or can modify the amount. If more information is required, can request additional details from dealer.',
        7: 'E-Invoice will be generated upon settlement initiation.',
        8: 'Got credit note from SAP. Review and send to dealer to complete the claim management process.',
      }
      : {
        // New 5-step flow
        1: 'Dealer submits the proposal for the activity with comments including proposal document with requested details, cost break-up, timeline for closure, and other requests',
        2: 'Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)',
        3: 'Department Lead approval. Decision point: Approved? (YES → Budget is blocked in the respective IO for the activity / NO → More clarification required → Request is cancelled)',
        4: 'Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description',
        5: 'Requestor approves the claim in full or can modify the amount. If more information is required, can request additional details from dealer.',
        6: 'E-Invoice will be generated upon settlement initiation.',
        7: 'Got credit note from SAP. Review and send to dealer to complete the claim management process.',
      };

    if (stepDescriptionMap[stepNumber]) {
      return stepDescriptionMap[stepNumber];
    }

    // Final fallback
    if (approverName && approverName !== 'Unknown' && approverName !== 'System') {
      return `${approverName} will review and approve this request.`;
    }

    return `Step ${stepNumber} approval required.`;
  };

  // Helper function to get version history for a specific approval level
  // Uses levelName to match history (consistent and doesn't change with step shifts or additional approvers)
  const getStepVersionHistory = (levelName: string) => {
    if (!versionHistory || versionHistory.length === 0 || !levelName) return { current: null, previous: null };

    // Filter history by levelName (most reliable and consistent)
    // Level names are consistent: "Dealer Proposal Submission", "Department Lead Approval", etc.
    // Additional approvers have unique names like "Additional Approver - John Doe"
    const stepVersions = versionHistory.filter((history: any) => {
      // Primary match: by levelName (consistent identifier)
      if (history.levelName && history.levelName.trim() === levelName.trim()) {
        return true; // Include all snapshot types for this level
      }

      // Fallback: match by levelName from snapshotData (for approval snapshots)
      if (history.snapshotData?.levelName && history.snapshotData.levelName.trim() === levelName.trim()) {
        return true;
      }

      return false;
    });

    // Sort by version descending to get most recent first
    // Prioritize APPROVE snapshots over WORKFLOW snapshots for the same version
    // This ensures approval comments are shown instead of just workflow movement
    const sortedVersions = [...stepVersions].sort((a, b) => {
      // First sort by version (descending)
      if (b.version !== a.version) {
        return b.version - a.version;
      }
      // If same version, prioritize APPROVE over WORKFLOW
      const aPriority = a.snapshotType === 'APPROVE' ? 1 : a.snapshotType === 'PROPOSAL' ? 2 : a.snapshotType === 'COMPLETION' ? 2 : 3;
      const bPriority = b.snapshotType === 'APPROVE' ? 1 : b.snapshotType === 'PROPOSAL' ? 2 : b.snapshotType === 'COMPLETION' ? 2 : 3;
      return aPriority - bPriority;
    });

    // Filter out WORKFLOW snapshots if there's an APPROVE snapshot for the same level
    // This ensures we show APPROVE snapshots (with comments) instead of WORKFLOW snapshots
    const filteredVersions = sortedVersions.filter((version, _index, arr) => {
      // If this is a WORKFLOW snapshot, check if there's an APPROVE snapshot with same or higher version
      if (version.snapshotType === 'WORKFLOW') {
        const hasApproveSnapshot = arr.some(v =>
          v.snapshotType === 'APPROVE' &&
          v.levelName === version.levelName &&
          v.version >= version.version
        );
        // Only keep WORKFLOW snapshot if there's no APPROVE snapshot
        return !hasApproveSnapshot;
      }
      // Keep all non-WORKFLOW snapshots
      return true;
    });

    const current = filteredVersions.length > 0 ? filteredVersions[0] : null;
    const previous = filteredVersions.length > 1 ? filteredVersions[1] : null;

    return { current, previous, all: filteredVersions };
  };


  // Get backend currentLevel to determine which steps are active vs waiting
  // This needs to be calculated before mapping steps so we can use it in status normalization
  // Convert to number to ensure proper comparison
  const backendCurrentLevel = request?.currentLevel || request?.current_level || request?.currentStep;
  const currentLevelNumber = backendCurrentLevel !== undefined && backendCurrentLevel !== null
    ? Number(backendCurrentLevel)
    : null;

  // Check request status - if rejected or closed, no steps should be active
  const requestStatus = (request?.status || '').toUpperCase();
  const isRequestRejected = requestStatus === 'REJECTED';
  const isRequestClosed = requestStatus === 'CLOSED';
  const isRequestActive = !isRequestRejected && !isRequestClosed &&
    (requestStatus === 'PENDING' || requestStatus === 'IN_PROGRESS' || requestStatus === 'IN-PROGRESS');

  // Find the rejected step level (if any) - all steps after rejection should be inactive
  const rejectedStepLevel = approvalFlow.find((level: any) => {
    const levelId = level.levelId || level.level_id;
    const approval = request?.approvals?.find((a: any) => a.levelId === levelId);
    return approval?.status?.toLowerCase() === 'rejected';
  });
  const rejectedStepNumber = rejectedStepLevel
    ? Number(rejectedStepLevel.levelNumber || rejectedStepLevel.level_number || rejectedStepLevel.step || 0)
    : null;

  // Transform approval flow to dealer claim workflow steps
  const workflowSteps: WorkflowStep[] = approvalFlow.map((step: any, index: number) => {
    // Get actual step number from levelNumber or step field - ensure it's a number
    const actualStepNumber = Number(step.levelNumber || step.level_number || step.step || index + 1);

    // Get levelName from the approval level if available
    const levelName = step.levelName || step.level_name;

    // Find approval data for this step
    const approval = request?.approvals?.find((a: any) => a.levelId === step.levelId);

    // Extract IO details from internalOrder table (Department Lead step - check by levelName)
    let ioDetails = undefined;
    const isDeptLeadStep = levelName && levelName.toLowerCase().includes('department lead');
    if (isDeptLeadStep || actualStepNumber === 3) {
      // Get IO details from dedicated internalOrder table
      const internalOrder = request?.internalOrder || request?.internal_order;

      if (internalOrder?.ioNumber || internalOrder?.io_number) {
        ioDetails = {
          ioNumber: internalOrder.ioNumber || internalOrder.io_number || '',
          blockedAmount: internalOrder.ioBlockedAmount || internalOrder.io_blocked_amount || 0,
          availableBalance: internalOrder.ioAvailableBalance || internalOrder.io_available_balance || 0,
          remainingBalance: internalOrder.ioRemainingBalance || internalOrder.io_remaining_balance || 0,
          organizedBy:
            internalOrder.organizer?.displayName ||
            internalOrder.organizer?.name ||
            internalOrder.organizedBy ||
            step.approver ||
            'N/A',
          organizedAt:
            internalOrder.organizedAt ||
            internalOrder.organized_at ||
            step.approvedAt ||
            request?.updatedAt ||
            '',
        };
      }
    }

    // Extract DMS details from approval data (Step 6)
    let dmsDetails = undefined;
    if (actualStepNumber === 6) {
      if (approval?.dmsDetails) {
        dmsDetails = {
          dmsNumber: approval.dmsDetails.dmsNumber || '',
          dmsRemarks: approval.dmsDetails.dmsRemarks || '',
          pushedBy: approval.dmsDetails.pushedBy || step.approver,
          pushedAt: approval.dmsDetails.pushedAt || step.approvedAt || '',
        };
      } else if (request?.dmsNumber) {
        // Fallback to request-level DMS data
        dmsDetails = {
          dmsNumber: request.dmsNumber || '',
          dmsRemarks: request.dmsRemarks || request.dmsDetails?.dmsRemarks || '',
          pushedBy: step.approver,
          pushedAt: step.approvedAt || request.updatedAt || '',
        };
      }
    }

    // Normalize status - CRITICAL: Check request status first, then step position
    // If request is rejected/closed, no steps should be active after rejection point
    let normalizedStatus: string;

    // FIRST: Check if request is rejected/closed - if so, handle accordingly
    if (isRequestRejected || isRequestClosed) {
      // If this step was rejected, mark it as rejected
      if (approval?.status?.toLowerCase() === 'rejected') {
        normalizedStatus = 'rejected';
      }
      // If there's a rejected step and this step comes after it, mark as waiting (inactive)
      else if (rejectedStepNumber !== null && actualStepNumber > rejectedStepNumber) {
        normalizedStatus = 'waiting';
      }
      // If this step was approved before rejection, keep it as approved
      else if (approval?.status?.toLowerCase() === 'approved') {
        normalizedStatus = 'approved';
      }
      // For steps before rejection that weren't explicitly approved/rejected
      else if (rejectedStepNumber !== null && actualStepNumber < rejectedStepNumber) {
        // Check if step was approved
        if (approval?.status?.toLowerCase() === 'approved') {
          normalizedStatus = 'approved';
        } else {
          normalizedStatus = 'waiting';
        }
      }
      // If no rejected step found but request is rejected, check current level
      else if (currentLevelNumber !== null && actualStepNumber > currentLevelNumber) {
        normalizedStatus = 'waiting';
      }
      // Default: mark as waiting (inactive) for rejected/closed requests
      else {
        normalizedStatus = 'waiting';
      }
    }
    // SECOND: Request is active - check step position relative to currentLevel
    else if (isRequestActive && currentLevelNumber !== null && currentLevelNumber > 0) {
      if (actualStepNumber > currentLevelNumber) {
        // Future step - MUST be waiting (ignore approval status and step.status)
        normalizedStatus = 'waiting';
      } else if (actualStepNumber < currentLevelNumber) {
        // Past step - should be approved/rejected
        // Use approval status if available, otherwise default to waiting
        if (approval?.status) {
          const approvalStatus = approval.status.toLowerCase();
          if (approvalStatus === 'approved') {
            normalizedStatus = 'approved';
          } else if (approvalStatus === 'skipped') {
            normalizedStatus = 'skipped';
          } else if (approvalStatus === 'rejected') {
            normalizedStatus = 'rejected';
          } else {
            normalizedStatus = 'waiting'; // Past step with unexpected status
          }
        } else {
          normalizedStatus = 'waiting'; // Past step with no approval
        }
      } else {
        // Current step - use approval status if available, otherwise use step.status
        if (approval?.status) {
          const approvalStatus = approval.status.toLowerCase();
          if (approvalStatus === 'approved') {
            normalizedStatus = 'approved';
          } else if (approvalStatus === 'rejected') {
            normalizedStatus = 'rejected';
          } else if (approvalStatus === 'pending' || approvalStatus === 'in_progress' || approvalStatus === 'in-progress') {
            normalizedStatus = 'in_progress';
          } else {
            normalizedStatus = 'in_progress'; // Default for current step
          }
        } else {
          // No approval object - normalize step.status
          const stepStatus = (step.status || 'pending').toLowerCase();
          if (stepStatus === 'in-review' || stepStatus === 'in_review' || stepStatus === 'in review' || stepStatus === 'pending') {
            normalizedStatus = 'in_progress';
          } else {
            normalizedStatus = stepStatus;
          }
        }
      }
    }
    // THIRD: No backend currentLevel or request status unclear - use approval status
    else {
      if (approval?.status) {
        const approvalStatus = approval.status.toLowerCase();
        if (approvalStatus === 'approved') {
          normalizedStatus = 'approved';
        } else if (approvalStatus === 'rejected') {
          normalizedStatus = 'rejected';
        } else if (approvalStatus === 'pending' || approvalStatus === 'in_progress' || approvalStatus === 'in-progress') {
          normalizedStatus = 'in_progress';
        } else {
          normalizedStatus = (step.status || 'waiting').toLowerCase();
        }
      } else {
        // No approval and no currentLevel - normalize step.status
        const stepStatus = (step.status || 'waiting').toLowerCase();
        if (stepStatus === 'in-review' || stepStatus === 'in_review' || stepStatus === 'in review' || stepStatus === 'pending') {
          normalizedStatus = 'in_progress';
        } else {
          normalizedStatus = stepStatus;
        }
      }
    }

    // Business logic: Only show elapsed time for active or completed steps
    // Waiting steps (future steps) should have elapsedHours = 0
    // This ensures that when in step 1, only step 1 shows elapsed time, others show 0
    const isWaiting = normalizedStatus === 'waiting';

    // Only calculate/show elapsed hours for active or completed steps
    // For waiting steps, elapsedHours should be 0 (they haven't started yet)
    const elapsedHours = isWaiting ? 0 : (step.elapsedHours || 0);

    const approverName = step.approver || step.approverName || 'Unknown';

    // Get levelName for this step (consistent identifier, doesn't change with step shifts)
    // Level names are consistent: "Dealer Proposal Submission", "Department Lead Approval", etc.
    // Additional approvers have unique names like "Additional Approver - John Doe"

    // Get version history for this step using levelName (consistent and reliable)
    const stepVersionHistory = levelName ? getStepVersionHistory(levelName) : { current: null, previous: null };

    return {
      step: actualStepNumber,
      title: getStepTitle(actualStepNumber, levelName, approverName),
      approver: approverName,
      description: getStepDescription(actualStepNumber, levelName, approverName) || step.description || '',
      tatHours: step.tatHours || 24,
      status: normalizedStatus as any,
      comment: step.comment || approval?.comment,
      approvedAt: step.approvedAt || approval?.timestamp,
      elapsedHours, // Only non-zero for active/completed steps
      ioDetails,
      dmsDetails,
      einvoiceUrl: actualStepNumber === 7 ? (approval as any)?.einvoiceUrl : undefined,
      emailTemplateUrl: (approval as any)?.emailTemplateUrl || undefined,
      versionHistory: stepVersionHistory, // Add version history to step
    };
  });

  // Calculate currentStep from approval flow - find the first pending or in_progress step
  // IMPORTANT: Use the workflow's currentLevel from backend (most accurate)
  // Fallback to finding first pending step if currentLevel not available
  // Note: Status normalization already handled in workflowSteps mapping above
  // backendCurrentLevel is already calculated above before the map function

  //: If request is rejected or closed, no step should be active
  let activeStep = null;
  let currentStep = 1;

  if (isRequestRejected || isRequestClosed) {
    // Request is rejected/closed - no active step
    // Find the rejected step to show as the "current" step for display purposes
    if (rejectedStepNumber !== null) {
      currentStep = rejectedStepNumber;
    } else if (currentLevelNumber !== null) {
      currentStep = currentLevelNumber;
    } else {
      currentStep = request?.currentStep || 1;
    }
  } else if (isRequestActive) {
    // Request is active - find the active step
    // Find the step that matches backend's currentLevel
    const activeStepFromBackend = currentLevelNumber !== null
      ? workflowSteps.find(s => s.step === currentLevelNumber)
      : null;

    // If backend currentLevel exists and step is pending/in_progress, use it
    // Otherwise, find first pending/in_progress step
    activeStep = activeStepFromBackend &&
      (activeStepFromBackend.status === 'pending' || activeStepFromBackend.status === 'in_progress')
      ? activeStepFromBackend
      : workflowSteps.find(s => {
        const status = s.status?.toLowerCase() || '';
        return status === 'pending' || status === 'in_progress' || status === 'in-review' || status === 'in_review';
      });

    currentStep = activeStep ? activeStep.step : (currentLevelNumber || request?.currentStep || 1);
  } else {
    // Request status unclear - use backend currentLevel or default
    currentStep = currentLevelNumber || request?.currentStep || 1;
  }

  // Check if current user is the dealer (for steps 1 and 5)
  const userEmail = (user as any)?.email?.toLowerCase() || '';
  const dealerEmail = (
    (request as any)?.dealerEmail?.toLowerCase() ||
    (request as any)?.dealer?.email?.toLowerCase() ||
    (request as any)?.claimDetails?.dealerEmail?.toLowerCase() ||
    (request as any)?.claimDetails?.dealer_email?.toLowerCase() ||
    ''
  );
  const isDealer = dealerEmail && userEmail === dealerEmail;

  // Check if current user is the approver for the current step
  const currentApprovalLevel = approvalFlow.find((level: any) =>
    (level.step || level.levelNumber || level.level_number) === currentStep
  );
  const approverEmail = (currentApprovalLevel?.approverEmail || '').toLowerCase();
  const isCurrentApprover = approverEmail && userEmail === approverEmail;

  // Find the initiator's step dynamically (Requestor Evaluation step)
  // This handles cases where approvers are added between steps, causing step numbers to shift
  const initiatorEmail = (
    (request as any)?.initiator?.email?.toLowerCase() ||
    (request as any)?.initiatorEmail?.toLowerCase() ||
    ''
  );

  // Find the step where the initiator is the approver
  // Check by: 1) approverEmail matches initiatorEmail, OR 2) levelName contains "Requestor Evaluation"
  const initiatorStepLevel = approvalFlow.find((l: any) => {
    const levelApproverEmail = (l.approverEmail || '').toLowerCase();
    const levelName = (l.levelName || '').toLowerCase();
    return (initiatorEmail && levelApproverEmail === initiatorEmail) ||
      levelName.includes('requestor evaluation') ||
      levelName.includes('requestor') && levelName.includes('confirmation');
  });

  const initiatorStepNumber = initiatorStepLevel
    ? (initiatorStepLevel.step || initiatorStepLevel.levelNumber || initiatorStepLevel.level_number || 2)
    : 2; // Fallback to 2 if not found

  // Check if user is approver for the initiator's step (requestor evaluation)
  const step2Level = initiatorStepLevel || approvalFlow.find((l: any) => (l.step || l.levelNumber || l.level_number) === 2);
  const step2ApproverEmail = (step2Level?.approverEmail || '').toLowerCase();
  const isStep2Approver = step2ApproverEmail && userEmail === step2ApproverEmail;

  // Check if user is approver for step 1 (dealer proposal submission) - match by email
  const step1Level = approvalFlow.find((l: any) => (l.step || l.levelNumber || l.level_number) === 1);
  const step1ApproverEmail = (step1Level?.approverEmail || '').toLowerCase();
  const isStep1Approver = step1ApproverEmail && userEmail === step1ApproverEmail;

  // Find Department Lead step dynamically (handles step shifts)
  const deptLeadStepLevel = approvalFlow.find((l: any) => {
    const levelName = (l.levelName || '').toLowerCase();
    return levelName.includes('department lead');
  });
  const step3ApproverEmail = (deptLeadStepLevel?.approverEmail || '').toLowerCase();
  const isStep3Approver = step3ApproverEmail && userEmail === step3ApproverEmail;

  // Handle proposal submission
  const handleProposalSubmit = async (data: {
    proposalDocument: File | null;
    costBreakup: Array<{ id: string; description: string; amount: number }>;
    expectedCompletionDate: string;
    otherDocuments: File[];
    dealerComments: string;
  }) => {
    try {
      if (!request?.id && !request?.requestId) {
        throw new Error('Request ID not found');
      }

      const requestId = request.id || request.requestId;

      // Upload proposal document if provided
      if (data.proposalDocument) {
        await uploadDocument(data.proposalDocument, requestId, 'APPROVAL');
      }

      // Upload other supporting documents
      for (const file of data.otherDocuments) {
        await uploadDocument(file, requestId, 'SUPPORTING');
      }

      // Submit proposal using dealer claim API (calculate total from inclusive item totals)
      const totalBudget = data.costBreakup.reduce((sum, item: any) => sum + (item.totalAmt || item.amount || 0), 0);
      await submitProposal(requestId, {
        proposalDocument: data.proposalDocument || undefined,
        costBreakup: data.costBreakup.map((item: any) => ({
          description: item.description,
          amount: item.amount,
          gstRate: item.gstRate,
          gstAmt: item.gstAmt,
          cgstRate: item.cgstRate,
          cgstAmt: item.cgstAmt,
          sgstRate: item.sgstRate,
          sgstAmt: item.sgstAmt,
          igstRate: item.igstRate,
          igstAmt: item.igstAmt,
          utgstRate: item.utgstRate,
          utgstAmt: item.utgstAmt,
          cessRate: item.cessRate,
          cessAmt: item.cessAmt,
          totalAmt: item.totalAmt,
          quantity: item.quantity,
          hsnCode: item.hsnCode,
          isService: item.isService
        })),
        totalEstimatedBudget: totalBudget,
        expectedCompletionDate: data.expectedCompletionDate,
        dealerComments: data.dealerComments,
      });

      // Activity is logged by backend service - no need to create work note
      toast.success('Proposal submitted successfully');
      handleRefresh();
    } catch (error: any) {
      console.error('Failed to submit proposal:', error);
      const errorMessage = error?.response?.data?.message || error?.message || 'Failed to submit proposal. Please try again.';
      toast.error(errorMessage);
      throw error;
    }
  };

  // Handle proposal approval
  const handleProposalApprove = async (comments: string) => {
    try {
      if (!request?.id && !request?.requestId) {
        throw new Error('Request ID not found');
      }

      const requestId = request.id || request.requestId;

      // Get approval levels to find the initiator's step levelId dynamically
      const details = await getWorkflowDetails(requestId);
      const approvals = details?.approvalLevels || details?.approvals || [];

      // Find the initiator's step by checking approverEmail or levelName
      const initiatorEmail = (
        (request as any)?.initiator?.email?.toLowerCase() ||
        (request as any)?.initiatorEmail?.toLowerCase() ||
        ''
      );

      const step2Level = approvals.find((level: any) => {
        const levelApproverEmail = (level.approverEmail || level.approver_email || '').toLowerCase();
        const levelName = (level.levelName || level.level_name || '').toLowerCase();
        const levelNumber = level.levelNumber || level.level_number;

        // Check if this is the initiator's step
        return (initiatorEmail && levelApproverEmail === initiatorEmail) ||
          levelName.includes('requestor evaluation') ||
          (levelName.includes('requestor') && levelName.includes('confirmation')) ||
          // Fallback: if initiatorStepNumber was found earlier, use it
          (levelNumber === initiatorStepNumber);
      }) || approvals.find((level: any) =>
        (level.levelNumber || level.level_number) === 2
      ); // Final fallback to level 2

      if (!step2Level?.levelId && !step2Level?.level_id) {
        throw new Error('Initiator approval level not found');
      }

      const levelId = step2Level.levelId || step2Level.level_id;

      // Approve the initiator's step using real API
      await approveLevel(requestId, levelId, comments);

      // Activity is logged by backend approval service - no need to create work note
      toast.success('Proposal approved successfully');
      handleRefresh();
    } catch (error: any) {
      console.error('Failed to approve proposal:', error);
      const errorMessage = error?.response?.data?.message || error?.message || 'Failed to approve proposal. Please try again.';
      toast.error(errorMessage);
      throw error;
    }
  };

  // Handle proposal rejection
  const handleProposalReject = async (comments: string) => {
    try {
      if (!request?.id && !request?.requestId) {
        throw new Error('Request ID not found');
      }

      const requestId = request.id || request.requestId;

      // Get approval levels to find the initiator's step levelId dynamically
      const details = await getWorkflowDetails(requestId);
      const approvals = details?.approvalLevels || details?.approvals || [];

      // Find the initiator's step by checking approverEmail or levelName
      const initiatorEmail = (
        (request as any)?.initiator?.email?.toLowerCase() ||
        (request as any)?.initiatorEmail?.toLowerCase() ||
        ''
      );

      const step2Level = approvals.find((level: any) => {
        const levelApproverEmail = (level.approverEmail || level.approver_email || '').toLowerCase();
        const levelName = (level.levelName || level.level_name || '').toLowerCase();
        const levelNumber = level.levelNumber || level.level_number;

        // Check if this is the initiator's step
        return (initiatorEmail && levelApproverEmail === initiatorEmail) ||
          levelName.includes('requestor evaluation') ||
          (levelName.includes('requestor') && levelName.includes('confirmation')) ||
          // Fallback: if initiatorStepNumber was found earlier, use it
          (levelNumber === initiatorStepNumber);
      }) || approvals.find((level: any) =>
        (level.levelNumber || level.level_number) === 2
      ); // Final fallback to level 2

      if (!step2Level?.levelId && !step2Level?.level_id) {
        throw new Error('Initiator approval level not found');
      }

      const levelId = step2Level.levelId || step2Level.level_id;

      // Reject the initiator's step using real API
      await rejectLevel(requestId, levelId, 'Proposal rejected by requestor', comments);

      // Activity is logged by backend approval service - no need to create work note
      toast.success('Proposal rejected. Request has been cancelled.');
      handleRefresh();
    } catch (error: any) {
      console.error('Failed to reject proposal:', error);
      const errorMessage = error?.response?.data?.message || error?.message || 'Failed to reject proposal. Please try again.';
      toast.error(errorMessage);
      throw error;
    }
  };

  // Handle proposal revision request
  const handleProposalRevision = async (comments: string) => {
    try {
      if (!request?.id && !request?.requestId) {
        throw new Error('Request ID not found');
      }

      const requestId = request.id || request.requestId;

      // Get approval levels to find the initiator's step levelId dynamically
      const details = await getWorkflowDetails(requestId);
      const approvals = details?.approvalLevels || details?.approvals || [];

      // Find the initiator's step by checking approverEmail or levelName
      const initiatorEmail = (
        (request as any)?.initiator?.email?.toLowerCase() ||
        (request as any)?.initiatorEmail?.toLowerCase() ||
        ''
      );

      const step2Level = approvals.find((level: any) => {
        const levelApproverEmail = (level.approverEmail || level.approver_email || '').toLowerCase();
        const levelName = (level.levelName || level.level_name || '').toLowerCase();
        const levelNumber = level.levelNumber || level.level_number;

        // Check if this is the initiator's step
        return (initiatorEmail && levelApproverEmail === initiatorEmail) ||
          levelName.includes('requestor evaluation') ||
          (levelName.includes('requestor') && levelName.includes('confirmation')) ||
          // Fallback: if initiatorStepNumber was found earlier, use it
          (levelNumber === initiatorStepNumber);
      }) || approvals.find((level: any) =>
        (level.levelNumber || level.level_number) === 2
      ); // Final fallback to level 2

      if (!step2Level?.levelId && !step2Level?.level_id) {
        throw new Error('Initiator approval level not found');
      }

      const levelId = step2Level.levelId || step2Level.level_id;

      // Reject the initiator's step using real API with Revision Requested reason
      // This will trigger the backend to return the workflow to the previous step (Dealer)
      await rejectLevel(requestId, levelId, 'Revised Quotation Requested', comments);

      // Activity is logged by backend approval service - no need to create work note
      toast.success('Revision requested. Request returned to dealer.');
      handleRefresh();
    } catch (error: any) {
      console.error('Failed to request revision:', error);
      const errorMessage = error?.response?.data?.message || error?.message || 'Failed to request revision. Please try again.';
      toast.error(errorMessage);
      throw error;
    }
  };

  // Handle re-quotation request from Claim Approval step (Step 6)
  const handleClaimReQuotation = async (comments: string) => {
    try {
      if (!request?.id && !request?.requestId) {
        throw new Error('Request ID not found');
      }

      const requestId = request.id || request.requestId;

      // Get workflow details to find the Requestor Claim Approval levelId dynamically
      const details = await getWorkflowDetails(requestId);
      const approvals = details?.approvalLevels || details?.approvals || [];

      // Find the Requestor Claim Approval step
      const claimApprovalLevel = approvals.find((level: any) => {
        const levelName = (level.levelName || level.level_name || '').toLowerCase();
        return levelName.includes('requestor claim') || levelName.includes('requestor - claim');
      });

      if (!claimApprovalLevel?.levelId && !claimApprovalLevel?.level_id) {
        throw new Error('Claim approval level not found');
      }

      const levelId = claimApprovalLevel.levelId || claimApprovalLevel.level_id;

      // Reject the claim approval step with 'Revised Quotation Requested'
      // This will trigger the backend to return the workflow to the Dealer Proposal step
      await rejectLevel(requestId, levelId, 'Revised Quotation Requested', comments);

      toast.success('Re-quotation requested. Request returned to dealer.');
      handleRefresh();
    } catch (error: any) {
      console.error('Failed to request re-quotation:', error);
      const errorMessage = error?.response?.data?.message || error?.message || 'Failed to request re-quotation. Please try again.';
      toast.error(errorMessage);
      throw error;
    }
  };

  // Handle IO approval (Department Lead step - found dynamically)
  const handleIOApproval = async (data: {
    ioNumber: string;
    comments: string;
  }) => {
    try {
      if (!request?.id && !request?.requestId) {
        throw new Error('Request ID not found');
      }

      const requestId = request.id || request.requestId;

      // Get approval levels to find Department Lead step levelId dynamically
      const details = await getWorkflowDetails(requestId);
      const approvals = details?.approvalLevels || details?.approvals || [];

      // Find Department Lead step by levelName (handles step shifts)
      const step3Level = approvals.find((level: any) => {
        const levelName = (level.levelName || level.level_name || '').toLowerCase();
        return levelName.includes('department lead');
      }) || approvals.find((level: any) =>
        (level.levelNumber || level.level_number) === 3
      ); // Fallback to level 3

      if (!step3Level?.levelId && !step3Level?.level_id) {
        throw new Error('Department Lead approval level not found');
      }

      const levelId = step3Level.levelId || step3Level.level_id;

      // First, update IO details using dealer claim API (if needed)
      // Only pass ioNumber - don't override existing balance values
      // Balance values should already be stored when amount was blocked earlier
      await updateIODetails(requestId, {
        ioNumber: data.ioNumber,
        // Don't pass balance fields - let backend preserve existing values
      });

      // Approve Step 3 using real API
      await approveLevel(requestId, levelId, data.comments);

      // Activity is logged by backend approval service - no need to create work note
      toast.success('Request approved and IO organized successfully');
      handleRefresh();
    } catch (error: any) {
      console.error('Failed to approve and organize IO:', error);
      const errorMessage = error?.response?.data?.message || error?.message || 'Failed to approve request. Please try again.';
      toast.error(errorMessage);
      throw error;
    }
  };

  // Handle completion documents submission (Step 5)
  const handleCompletionSubmit = async (data: {
    activityCompletionDate: string;
    numberOfParticipants?: number;
    closedExpenses: Array<{ id: string; description: string; amount: number }>;
    totalClosedExpenses: number;
    completionDocuments: File[];
    activityPhotos: File[];
    invoicesReceipts?: File[];
    attendanceSheet?: File;
    completionDescription: string;
  }) => {
    try {
      if (!request?.id && !request?.requestId) {
        throw new Error('Request ID not found');
      }

      const requestId = request.id || request.requestId;

      // Transform expense items to match API format (include GST fields)
      const closedExpenses = data.closedExpenses.map((item: any) => ({
        description: item.description,
        amount: item.amount,
        gstRate: item.gstRate,
        gstAmt: item.gstAmt,
        cgstRate: item.cgstRate,
        cgstAmt: item.cgstAmt,
        sgstRate: item.sgstRate,
        sgstAmt: item.sgstAmt,
        igstRate: item.igstRate,
        igstAmt: item.igstAmt,
        utgstRate: item.utgstRate,
        utgstAmt: item.utgstAmt,
        cessRate: item.cessRate,
        cessAmt: item.cessAmt,
        totalAmt: item.totalAmt,
        quantity: item.quantity,
        hsnCode: item.hsnCode,
        isService: item.isService
      }));

      // Submit completion documents using dealer claim API
      await submitCompletion(requestId, {
        activityCompletionDate: data.activityCompletionDate,
        numberOfParticipants: data.numberOfParticipants,
        closedExpenses,
        totalClosedExpenses: data.totalClosedExpenses,
        completionDocuments: data.completionDocuments,
        activityPhotos: data.activityPhotos,
        completionDescription: data.completionDescription,
      });

      // Upload supporting documents if provided
      if (data.invoicesReceipts && data.invoicesReceipts.length > 0) {
        for (const file of data.invoicesReceipts) {
          await uploadDocument(file, requestId, 'SUPPORTING');
        }
      }

      if (data.attendanceSheet) {
        await uploadDocument(data.attendanceSheet, requestId, 'SUPPORTING');
      }

      // Activity is logged by backend service - no need to create work note
      toast.success('Completion documents submitted successfully');
      handleRefresh();
    } catch (error: any) {
      console.error('Failed to submit completion documents:', error);
      const errorMessage = error?.response?.data?.message || error?.message || 'Failed to submit completion documents. Please try again.';
      toast.error(errorMessage);
      throw error;
    }
  };

  // Handle E-Invoice generation (Step 6)
  const handleDMSPush = async (_comments: string) => {
    try {
      if (!request?.id && !request?.requestId) {
        throw new Error('Request ID not found');
      }

      const requestId = request.id || request.requestId;

      // Call API to push to DMS (this will auto-generate e-invoice)
      // eInvoiceDate is required, so we pass current date
      const today = new Date().toISOString().slice(0, 10);
      await updateEInvoice(requestId as string, {
        eInvoiceDate: today,
      });

      // Activity is logged by backend service - no need to create work note
      toast.success('E-Invoice generation initiated successfully.');
      handleRefresh();
    } catch (error: any) {
      console.error('[DealerClaimWorkflowTab] Error generating e-invoice:', error);
      // Backend now translates PWC error codes to user-friendly messages in 'message' field
      // Prefer 'message' (user-friendly) over 'error' (raw technical details)
      const responseMessage = error?.response?.data?.message;
      let errorMessage = responseMessage || error?.message || 'E-Invoice generation failed. Please try again.';
      // Truncate very long error messages for toast display (keep first 300 chars)
      if (errorMessage.length > 300) {
        errorMessage = errorMessage.substring(0, 300) + '...';
      }
      toast.error(errorMessage);
      throw error;
    }
  };

  // Handle IO rejection (Step 3)
  const handleIORejection = async (comments: string) => {
    try {
      if (!request?.id && !request?.requestId) {
        throw new Error('Request ID not found');
      }

      const requestId = request.id || request.requestId;

      // Get approval levels to find Department Lead step levelId dynamically
      const details = await getWorkflowDetails(requestId);
      const approvals = details?.approvalLevels || details?.approvals || [];

      // Find Department Lead step by levelName (handles step shifts)
      const step3Level = approvals.find((level: any) => {
        const levelName = (level.levelName || level.level_name || '').toLowerCase();
        return levelName.includes('department lead');
      }) || approvals.find((level: any) =>
        (level.levelNumber || level.level_number) === 3
      ); // Fallback to level 3

      if (!step3Level?.levelId && !step3Level?.level_id) {
        throw new Error('Department Lead approval level not found');
      }

      const levelId = step3Level.levelId || step3Level.level_id;

      // Reject Department Lead step using real API
      await rejectLevel(requestId, levelId, 'Dept Lead rejected - More clarification required', comments);

      // Activity is logged by backend approval service - no need to create work note
      toast.success('Request rejected. Request has been cancelled.');
      handleRefresh();
    } catch (error: any) {
      console.error('Failed to reject request:', error);
      const errorMessage = error?.response?.data?.message || error?.message || 'Failed to reject request. Please try again.';
      toast.error(errorMessage);
      throw error;
    }
  };

  // Extract proposal data from request
  const [proposalData, setProposalData] = useState<any | null>(null);

  useEffect(() => {
    if (!request) {
      setProposalData(null);
      return;
    }

    const loadProposalData = async () => {
      try {
        const requestId = request.id || request.requestId;
        if (!requestId) {
          setProposalData(null);
          return;
        }

        // Get workflow details which includes documents and proposal details
        const details = await getWorkflowDetails(requestId);
        const documents = details?.documents || [];
        const proposalDetails = request.proposalDetails || details?.proposalDetails || {};

        // Find proposal document (category APPROVAL or type proposal)
        const proposalDoc = documents.find((d: any) =>
          d.category === 'APPROVAL' || d.type === 'proposal' || d.documentCategory === 'APPROVAL'
        );

        // Find supporting documents
        const otherDocs = documents.filter((d: any) =>
          d.category === 'SUPPORTING' || d.type === 'supporting' || d.documentCategory === 'SUPPORTING'
        );

        // Ensure costBreakup is an array
        let costBreakup = proposalDetails.costBreakup || [];
        if (typeof costBreakup === 'string') {
          try {
            costBreakup = JSON.parse(costBreakup);
          } catch (e) {
            console.warn('Failed to parse costBreakup JSON:', e);
            costBreakup = [];
          }
        }
        if (!Array.isArray(costBreakup)) {
          costBreakup = [];
        }

        setProposalData({
          proposalDocument: proposalDoc ? {
            name: proposalDoc.fileName || proposalDoc.file_name || proposalDoc.name,
            id: proposalDoc.documentId || proposalDoc.document_id || proposalDoc.id,
          } : undefined,
          costBreakup: costBreakup,
          expectedCompletionDate: proposalDetails.expectedCompletionDate || '',
          otherDocuments: otherDocs.map((d: any) => ({
            name: d.fileName || d.file_name || d.name,
            id: d.documentId || d.document_id || d.id,
          })),
          dealerComments: proposalDetails.dealerComments || '',
          submittedAt: proposalDetails.submittedAt,
        });
      } catch (error) {
        console.warn('Failed to load proposal data:', error);
        // Fallback to request data only
        const proposalDetails = request.proposalDetails || {};

        // Ensure costBreakup is an array
        let costBreakup = proposalDetails.costBreakup || [];
        if (typeof costBreakup === 'string') {
          try {
            costBreakup = JSON.parse(costBreakup);
          } catch (e) {
            console.warn('Failed to parse costBreakup JSON:', e);
            costBreakup = [];
          }
        }
        if (!Array.isArray(costBreakup)) {
          costBreakup = [];
        }

        setProposalData({
          proposalDocument: undefined,
          costBreakup: costBreakup,
          expectedCompletionDate: proposalDetails.expectedCompletionDate || '',
          otherDocuments: [],
          dealerComments: proposalDetails.dealerComments || '',
          submittedAt: proposalDetails.submittedAt,
        });
      }
    };

    loadProposalData();
  }, [request]);

  // Extract completion documents data from request/documents
  const [completionDocumentsData, setCompletionDocumentsData] = useState<any | null>(null);

  useEffect(() => {
    if (!request) {
      setCompletionDocumentsData(null);
      return;
    }

    const loadCompletionDocuments = async () => {
      try {
        const requestId = request.id || request.requestId;
        if (!requestId) {
          setCompletionDocumentsData(null);
          return;
        }

        // Get workflow details which includes all documents
        const details = await getWorkflowDetails(requestId);
        const documents = details?.documents || [];

        // Filter and categorize documents
        const completionDocs: any[] = [];
        const activityPhotos: any[] = [];
        const invoicesReceipts: any[] = [];
        let attendanceSheet: any = null;

        documents.forEach((doc: any) => {
          const category = (doc.category || doc.documentCategory || doc.type || '').toUpperCase();
          const name = (doc.fileName || doc.file_name || doc.name || '').toLowerCase();

          const docObj = {
            name: doc.fileName || doc.file_name || doc.name,
            id: doc.documentId || doc.document_id || doc.id,
            url: doc.url || doc.storageUrl || doc.storage_url,
          };

          if (category === 'COMPLETION' || category === 'COMPLETION_DOCUMENT') {
            completionDocs.push(docObj);
          } else if (category === 'ACTIVITY_PHOTO' || category === 'PHOTO' || category === 'IMAGE') {
            activityPhotos.push(docObj);
          } else if (category === 'ATTENDANCE' || category === 'ATTENDANCE_SHEET') {
            attendanceSheet = docObj;
          } else if (category === 'SUPPORTING' || category === 'INVOICE' || category === 'RECEIPT') {
            // Check if it's likely an attendance sheet based on name if not already found
            if (!attendanceSheet && (name.includes('attendance') || name.includes('participant'))) {
              attendanceSheet = docObj;
            } else {
              invoicesReceipts.push(docObj);
            }
          }
        });

        // If documents came from the completionDetails directly (some backends might structure it this way)
        if (completionDocs.length === 0 && activityPhotos.length === 0 && request.completionDetails) {
          // Try to extract from request.completionDetails if available/applicable
          // This is a fallback in case documents aren't flattened in the main documents list yet
        }

        setCompletionDocumentsData({
          completionDocuments: completionDocs,
          activityPhotos: activityPhotos,
          invoicesReceipts: invoicesReceipts,
          attendanceSheet: attendanceSheet,
        });

      } catch (error) {
        console.warn('Failed to load completion documents:', error);
        setCompletionDocumentsData(null);
      }
    };

    loadCompletionDocuments();
  }, [request]);

  const handleRetrigger = async () => {
    try {
      toast.loading('Retriggering WFM push...', { id: 'wfm-retrigger' });
      await retriggerWFMPush(request.id);
      toast.success('WFM push re-triggered successfully', { id: 'wfm-retrigger' });
      
      // Refresh the request data if onRefresh is provided
      if (onRefresh) {
        onRefresh();
      } else {
        // Fallback or full page refresh
        window.location.reload();
      }
    } catch (error: any) {
      console.error('Error retriggering WFM push:', error);
      toast.error(error.message || 'Failed to re-trigger WFM push', { id: 'wfm-retrigger' });
    }
  };

  const handleDownloadCSV = async () => {
    try {
      const requestId = request.id || request.requestId;
      if (!requestId) {
        toast.error('Request ID not found');
        return;
      }

      const baseUrl = import.meta.env.VITE_API_BASE_URL || '';
      const response = await fetch(`${baseUrl}/dealer-claims/${requestId}/e-invoice/csv`, {
        headers: {
          'Authorization': `Bearer ${TokenManager.getAccessToken() || ''}`
        },
        credentials: 'include'
      });

      if (!response.ok) {
        throw new Error('Failed to download CSV');
      }

      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `Invoice_${request.requestNumber || 'Export'}.csv`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
      toast.success('CSV downloaded successfully');
    } catch (error) {
      console.error('Error downloading CSV:', error);
      toast.error('Failed to download CSV');
    }
  };

  const handlePreviewInvoice = async () => {
    try {
      const requestId = request.id || request.requestId;
      if (!requestId) {
        toast.error('Request ID not found');
        return;
      }

      // Check if invoice exists
      if (!request.invoice && !request.irn) {
        toast.error('Invoice not generated yet');
        return;
      }

      setInvoicePdfLoading(true);
      setShowInvoicePdfModal(true);

      // Fetch PDF securely via Authorization header (not in URL query)
      const baseUrl = import.meta.env.VITE_API_BASE_URL || '';
      const response = await fetch(`${baseUrl}/dealer-claims/${requestId}/e-invoice/pdf`, {
        headers: {
          'Authorization': `Bearer ${TokenManager.getAccessToken() || ''}`
        },
        credentials: 'include'
      });

      if (!response.ok) {
        throw new Error('Failed to fetch invoice PDF');
      }

      const blob = await response.blob();
      const blobUrl = window.URL.createObjectURL(blob);

      // Revoke previous blob URL to prevent memory leaks
      if (invoicePdfUrl) {
        window.URL.revokeObjectURL(invoicePdfUrl);
      }

      setInvoicePdfUrl(blobUrl);
    } catch (error) {
      console.error('Failed to preview invoice:', error);
      toast.error('Failed to load invoice preview');
      setShowInvoicePdfModal(false);
    } finally {
      setInvoicePdfLoading(false);
    }
  };

  const handleCloseInvoicePdf = () => {
    setShowInvoicePdfModal(false);
    if (invoicePdfUrl) {
      window.URL.revokeObjectURL(invoicePdfUrl);
      setInvoicePdfUrl(null);
    }
  };

  const handleDownloadInvoicePdf = () => {
    if (invoicePdfUrl) {
      const a = document.createElement('a');
      a.href = invoicePdfUrl;
      a.download = `Invoice_${request.requestNumber || 'Download'}.pdf`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      toast.success('Invoice PDF downloaded');
    }
  };

  // Get dealer and activity info
  const dealerName = request?.claimDetails?.dealerName ||
    request?.dealerInfo?.name ||
    'Dealer';
  const dealerGSTIN = request?.claimDetails?.dealerGstin ||
    request?.dealerInfo?.gstin ||
    request?.dealerInfo?.dealerGSTIN;
  const activityName = request?.claimDetails?.activityName ||
    request?.activityInfo?.activityName ||
    request?.title ||
    'Activity';

  return (
    <>
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="flex items-center gap-2">
                <TrendingUp className="w-5 h-5 text-purple-600" />
                Claim Management Workflow
              </CardTitle>
              <CardDescription className="mt-2">
                Approval process for dealer claim management
              </CardDescription>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          {/* Returned to Initiator Banner */}

          {(() => {
            const isReturnedToInitiator = request?.status === 'rejected' &&
              !(request?.closureDate || request?.closure_date) && isInitiator;
            if (!isReturnedToInitiator) return null;

            return (
              <div className="mb-6 p-4 bg-amber-50 border-l-4 border-amber-500 rounded-lg flex items-start gap-4 shadow-sm">
                <div className="p-2 bg-amber-100 rounded-full">
                  <AlertTriangle className="w-5 h-5 text-amber-600" />
                </div>
                <div className="flex-1">
                  <h3 className="text-sm font-bold text-amber-900 mb-1">Action Required: Request Returned</h3>
                  <p className="text-xs text-amber-800 leading-relaxed mb-3">
                    This request has been returned to you by the department head.
                    {isInitiator ?
                      'You can choose to resubmit, discuss with the dealer, request a revision, or cancel the request.' :
                      'The initiator needs to take action to proceed.'}
                  </p>
                  {/* Actions are now in the step card itself - no need for separate button */}
                </div>
              </div>
            );
          })()}

          <div className="space-y-4">
            {workflowSteps.map((step, index) => {
              // Step is active if:
              // 1. Request is active (not rejected/closed)
              // 2. It's pending or in_progress
              // 3. AND it matches currentStep (from backend or calculated)
              // 4. AND it's the actual current step (not a future step that happens to be pending)
              const stepStatus = step.status?.toLowerCase() || '';
              const isPendingOrInProgress = stepStatus === 'in_progress';
              const matchesCurrentStep = step.step === currentStep;

              // Step is active only if:
              // - Request is active (not rejected/closed)
              // - AND it matches the current step 
              // - AND is pending/in_progress
              const isActive = isRequestActive && isPendingOrInProgress && matchesCurrentStep;
              const isCompleted = step.status === 'approved' || step.status === 'skipped';

              // Find approval data for this step to get SLA information
              // First find the corresponding level in approvalFlow to get levelId
              const stepLevel = approvalFlow.find((l: any) => (l.step || l.levelNumber || l.level_number) === step.step);
              const approval = stepLevel?.levelId
                ? request?.approvals?.find((a: any) => a.levelId === stepLevel.levelId || a.level_id === stepLevel.levelId)
                : null;

              // Check if step is paused
              const isPaused = approval?.status === 'PAUSED' ||
                (request?.pauseInfo?.isPaused &&
                  (request?.pauseInfo?.levelId === approval?.levelId ||
                    request?.pauseInfo?.level_id === approval?.levelId));

              return (
                <div
                  key={index}
                  className={`relative p-5 rounded-lg border-2 transition-all ${getStepCardStyle(step.status, isActive)}`}
                >
                  <div className="flex items-start gap-4">
                    {/* Step Icon */}
                    <div className={`p-3 rounded-xl ${getStepIconBg(step.status)}`}>
                      {getStepIcon(step.status)}
                    </div>

                    {/* Step Content */}
                    <div className="flex-1 min-w-0">
                      <div className="flex items-start justify-between gap-4 mb-2">
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-1">
                            <h4 className="font-semibold text-gray-900">
                              {step.title}
                            </h4>
                            <Badge className={getStepBadgeVariant(step.status)}>
                              {step.status.toLowerCase()}
                            </Badge>
                            {/* Email Template Button - Show when step has emailTemplateUrl and is approved */}
                            {step.emailTemplateUrl && step.status === 'approved' && (
                              <Button
                                variant="ghost"
                                size="sm"
                                className="h-6 w-6 p-0 hover:bg-blue-100"
                                title="View email template"
                                onClick={() => {
                                  setSelectedStepForEmail({ stepNumber: step.step, stepName: step.title });
                                  setShowEmailTemplateModal(true);
                                }}
                              >
                                <Mail className="w-3.5 h-3.5 text-blue-600" />
                              </Button>
                            )}
                            {/* E-Invoice Download Button (Step 7) */}
                            {step.step === 7 && step.einvoiceUrl && isCompleted && (
                              <Button
                                variant="ghost"
                                size="sm"
                                className="h-6 w-6 p-0 hover:bg-green-100"
                                title="Download E-Invoice"
                                onClick={() => window.open(step.einvoiceUrl, '_blank')}
                              >
                                <Download className="w-3.5 h-3.5 text-green-600" />
                              </Button>
                            )}
                            {/* Invoice Preview Button (Requestor Claim Approval) */}
                            {(() => {
                              const isRequestorClaimStep = (step.levelName || step.title || '').toLowerCase().includes('requestor claim') ||
                                (step.levelName || step.title || '').toLowerCase().includes('requestor - claim');
                              const hasInvoice = request?.invoice || (request?.irn && step.status === 'approved');
                              return isRequestorClaimStep && hasInvoice && (
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  className="h-6 w-6 p-0 hover:bg-amber-100"
                                  title="Preview Invoice"
                                  onClick={handlePreviewInvoice}
                                >
                                  <Receipt className="w-3.5 h-3.5 text-amber-600" />
                                </Button>
                              );
                            })()}
                             {/* CSV Export & WFM Push Status (Requestor Claim Approval) */}
                             {(() => {
                               const isRequestorClaimStep = (step.levelName || step.title || '').toLowerCase().includes('requestor claim') ||
                                 (step.levelName || step.title || '').toLowerCase().includes('requestor - claim');
                               const hasInvoice = request?.invoice || (request?.irn && step.status === 'approved');
                               const wfmStatus = request?.invoice?.wfmPushStatus || (request?.invoice as any)?.wfmPushStatus;
                               const wfmError = request?.invoice?.wfmPushError || (request?.invoice as any)?.wfmPushError;
                               
                               return isRequestorClaimStep && hasInvoice && (
                                 <div className="flex items-center gap-1 ml-1">
                                   <Button
                                     variant="ghost"
                                     size="sm"
                                     className="h-6 w-6 p-0 hover:bg-emerald-100"
                                     title="Export CSV"
                                     onClick={handleDownloadCSV}
                                   >
                                     <FileSpreadsheet className="w-3.5 h-3.5 text-emerald-600" />
                                   </Button>
                                   
                                   {/* WFM Push Status Indication */}
                                   {wfmStatus === 'SUCCESS' ? (
                                     <div title="Pushed to WFM successfully">
                                       <CheckCircle2 className="w-3.5 h-3.5 text-green-500" />
                                     </div>
                                   ) : wfmStatus === 'FAILED' ? (
                                     <div className="flex items-center gap-1">
                                       <div title={`WFM Push Failed: ${wfmError || 'Unknown error'}`}>
                                         <XCircle className="w-3.5 h-3.5 text-red-500" />
                                       </div>
                                       <Button
                                         variant="ghost"
                                         size="sm"
                                         className="h-5 px-1.5 text-[10px] text-red-600 hover:text-red-700 hover:bg-red-50 border border-red-200 h-auto py-0"
                                         onClick={handleRetrigger}
                                       >
                                         Retry Push
                                       </Button>
                                     </div>
                                   ) : (
                                     <div className="flex items-center gap-1">
                                       <div title="WFM Push Pending">
                                         <Clock className="w-3.5 h-3.5 text-amber-500" />
                                       </div>
                                       <Button
                                         variant="ghost"
                                         size="sm"
                                         className="h-5 px-1.5 text-[10px] text-amber-600 hover:text-amber-700 hover:bg-amber-50 border border-amber-200 h-auto py-0"
                                         onClick={handleRetrigger}
                                       >
                                         Push Now
                                       </Button>
                                     </div>
                                   )}
                                 </div>
                               );
                             })()}
                          </div>
                          <p className="text-sm text-gray-600">{step.approver}</p>
                          <p className="text-sm text-gray-500 mt-2 italic">{step.description}</p>
                        </div>
                        <div className="text-right">
                          <p className="text-xs text-gray-500">TAT: {formatHoursMinutes(step.tatHours)}</p>
                          {/* Only show elapsed time for active or completed steps, not for waiting steps */}
                          {step.elapsedHours && (isActive || isCompleted) && (
                            <p className="text-xs text-gray-600 font-medium">
                              Elapsed: {formatHoursMinutes(step.elapsedHours)}
                            </p>
                          )}
                        </div>
                      </div>

                      {/* Comment Section */}
                      {step.comment && (
                        <div className="mt-3 p-3 bg-white rounded-lg border border-gray-200">
                          <p className="text-sm text-gray-700">{step.comment}</p>
                        </div>
                      )}

                      {/* Version History Section */}
                      {step.versionHistory && step.versionHistory.all && step.versionHistory.all.length > 0 && (
                        <div className="mt-3">
                          <Button
                            variant="ghost"
                            size="sm"
                            className="w-full justify-between text-xs text-amber-700 hover:text-amber-800 hover:bg-amber-50"
                            onClick={() => {
                              const newExpanded = new Set(expandedVersionSteps);
                              if (newExpanded.has(step.step)) {
                                newExpanded.delete(step.step);
                              } else {
                                newExpanded.add(step.step);
                              }
                              setExpandedVersionSteps(newExpanded);
                            }}
                          >
                            <div className="flex items-center gap-2">
                              <History className="w-3.5 h-3.5" />
                              <span className="font-medium">Version History</span>
                              {step.versionHistory.all && step.versionHistory.all.length > 0 && (
                                <Badge className="bg-amber-100 text-amber-800 text-[10px] px-1.5 py-0">
                                  {step.versionHistory.all.length} Versions
                                </Badge>
                              )}
                            </div>
                            {expandedVersionSteps.has(step.step) ? (
                              <ChevronUp className="w-4 h-4" />
                            ) : (
                              <ChevronDown className="w-4 h-4" />
                            )}
                          </Button>

                          {expandedVersionSteps.has(step.step) && step.versionHistory.all && (
                            <div className="mt-2 space-y-3 p-3 bg-amber-50/50 rounded-lg border border-amber-200 text-left">
                              {step.versionHistory.all.map((version: any, vIndex: number) => (
                                <div key={vIndex} className={`space-y-2 ${vIndex > 0 ? 'pt-2 border-t border-amber-200' : ''}`}>
                                  <div className="flex items-center justify-between">
                                    <div className="flex items-center gap-2">
                                      <Badge className={`${vIndex === 0 ? 'bg-amber-500' : 'bg-gray-400'} text-white text-[10px] px-2 py-0.5`}>
                                        {vIndex === 0 ? 'Current' : 'Previous'}: v{version.version}
                                      </Badge>
                                      <span className="text-[10px] text-gray-600 font-medium">
                                        {formatDateSafe(version.createdAt)}
                                      </span>
                                    </div>
                                  </div>
                                  <p className="text-xs text-gray-700 font-medium">
                                    {version.changeReason || 'Version Update'}
                                  </p>
                                  <div className="flex items-center gap-1.5">
                                    <div className={`w-3 h-3 rounded-full ${vIndex === 0 ? 'bg-blue-100' : 'bg-gray-100'} flex items-center justify-center`}>
                                      <span className={`text-[8px] font-bold ${vIndex === 0 ? 'text-blue-600' : 'text-gray-600'}`}>
                                        {version.changer?.displayName?.charAt(0) || 'U'}
                                      </span>
                                    </div>
                                    <span className="text-[10px] text-gray-600">
                                      By {version.changer?.displayName || version.changer?.email || 'Unknown User'}
                                    </span>
                                  </div>

                                  {/* Show snapshot data if available - JSONB structure */}
                                  {version.snapshotType === 'PROPOSAL' && version.snapshotData && (
                                    <div className="mt-2 p-2 bg-white rounded border border-amber-200">
                                      <div className="flex justify-between items-start mb-2">
                                        <div>
                                          <p className="text-[10px] font-semibold text-gray-700">Proposal Snapshot</p>
                                          <p className="text-[10px] text-gray-600">
                                            Budget: ₹{Number(version.snapshotData.totalBudget || 0).toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                                          </p>
                                        </div>
                                        <button
                                          className="text-[10px] text-blue-600 hover:text-blue-800 hover:underline font-medium flex items-center gap-1 transition-colors"
                                          onClick={() => setViewSnapshot({
                                            data: version.snapshotData,
                                            type: 'PROPOSAL',
                                            title: `Proposal (v${version.version})`
                                          })}
                                        >
                                          <Eye className="w-3 h-3" />
                                          View Details
                                        </button>
                                      </div>

                                      {version.snapshotData.comments && (
                                        <p className="text-[10px] text-gray-600 mt-1 line-clamp-2">
                                          Comments: {version.snapshotData.comments}
                                        </p>
                                      )}
                                    </div>
                                  )}
                                  {version.snapshotType === 'INTERNAL_ORDER' && version.snapshotData && (
                                    <div className="mt-2 p-2 bg-white rounded border border-amber-200">
                                      <p className="text-[10px] font-semibold text-gray-700 mb-1">IO Block Snapshot:</p>
                                      <p className="text-[10px] text-gray-600">
                                        IO Number: {version.snapshotData.ioNumber || 'N/A'}
                                      </p>
                                      <p className="text-[10px] text-gray-600">
                                        Blocked Amount: ₹{Number(version.snapshotData.blockedAmount || 0).toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                                      </p>
                                      {version.snapshotData.sapDocumentNumber && (
                                        <p className="text-[10px] text-gray-600">
                                          SAP Doc: {version.snapshotData.sapDocumentNumber}
                                        </p>
                                      )}
                                    </div>
                                  )}
                                  {version.snapshotType === 'COMPLETION' && version.snapshotData && (
                                    <div className="mt-2 p-2 bg-white rounded border border-amber-200">
                                      <div className="flex justify-between items-start mb-2">
                                        <div>
                                          <p className="text-[10px] font-semibold text-gray-700">Completion Snapshot</p>
                                          <p className="text-[10px] text-gray-600">
                                            Total: ₹{Number(version.snapshotData.totalExpenses || 0).toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                                          </p>
                                        </div>
                                        <button
                                          className="text-[10px] text-blue-600 hover:text-blue-800 hover:underline font-medium flex items-center gap-1 transition-colors"
                                          onClick={() => setViewSnapshot({
                                            data: version.snapshotData,
                                            type: 'COMPLETION',
                                            title: `Completion (v${version.version})`
                                          })}
                                        >
                                          <Eye className="w-3 h-3" />
                                          View Details
                                        </button>
                                      </div>

                                      {version.snapshotData.comments && (
                                        <p className="text-[10px] text-gray-600 mt-1 line-clamp-2">
                                          Comments: {version.snapshotData.comments}
                                        </p>
                                      )}
                                    </div>
                                  )}
                                  {version.snapshotType === 'APPROVE' && version.snapshotData && (
                                    <div className="mt-2 p-2 bg-white rounded border border-amber-200">
                                      <p className="text-[10px] font-semibold text-gray-700 mb-1">
                                        {version.snapshotData.action === 'APPROVE' ? 'Approval' : 'Rejection'} Snapshot:
                                      </p>
                                      <p className="text-[10px] text-gray-600">
                                        By: {version.snapshotData.approverName || version.snapshotData.approverEmail || 'Unknown'}
                                      </p>
                                      {version.snapshotData.comments && (
                                        <p className="text-[10px] text-gray-600 mt-1">
                                          Comments: {version.snapshotData.comments.substring(0, 100)}
                                          {version.snapshotData.comments.length > 100 ? '...' : ''}
                                        </p>
                                      )}
                                      {version.snapshotData.rejectionReason && (
                                        <p className="text-[10px] text-red-600 mt-1">
                                          Rejection Reason: {version.snapshotData.rejectionReason.substring(0, 100)}
                                          {version.snapshotData.rejectionReason.length > 100 ? '...' : ''}
                                        </p>
                                      )}
                                    </div>
                                  )}
                                  {version.snapshotType === 'WORKFLOW' && version.snapshotData && version.snapshotData.comments && (
                                    <div className="mt-2 p-2 bg-white rounded border border-amber-200">
                                      <p className="text-[10px] font-semibold text-gray-700 mb-1">Approval Comment:</p>
                                      <p className="text-[10px] text-gray-600">
                                        {version.snapshotData.comments.substring(0, 100)}
                                        {version.snapshotData.comments.length > 100 ? '...' : ''}
                                      </p>
                                    </div>
                                  )}
                                </div>
                              ))}
                            </div>
                          )}
                        </div>
                      )}

                      {/* Active Approver - SLA Time Tracking (Only show for current active step) */}
                      {isActive && approval?.sla && (
                        <div className="mt-3 space-y-3">
                          <div className="flex items-center justify-between text-xs">
                            <span className="text-gray-600">Due by:</span>
                            <span className="font-medium text-gray-900">
                              {approval.sla.deadline ? formatDateDDMMYYYY(approval.sla.deadline, true) : 'Not set'}
                            </span>
                          </div>

                          {/* Current Approver - Time Tracking */}
                          <div className={`border rounded-lg p-3 ${isPaused ? 'bg-gray-100 border-gray-300' :
                            (approval.sla.percentageUsed || 0) >= 100 ? 'bg-red-50 border-red-200' :
                              (approval.sla.percentageUsed || 0) >= 75 ? 'bg-orange-50 border-orange-200' :
                                (approval.sla.percentageUsed || 0) >= 50 ? 'bg-amber-50 border-amber-200' :
                                  'bg-green-50 border-green-200'
                            }`}>
                            <p className="text-xs font-semibold text-gray-900 mb-3 flex items-center gap-2">
                              <Clock className="w-4 h-4" />
                              Current Approver - Time Tracking {isPaused && '(Paused)'}
                            </p>

                            <div className="space-y-2 text-xs mb-3">
                              <div className="flex justify-between">
                                <span className="text-gray-600">Time elapsed since assigned:</span>
                                <span className="font-medium text-gray-900">{approval.sla.elapsedText || '0 hours'}</span>
                              </div>
                              <div className="flex justify-between">
                                <span className="text-gray-600">Time used:</span>
                                <span className="font-medium text-gray-900">
                                  {approval.sla.elapsedText || '0 hours'} / {formatHoursMinutes(step.tatHours)} allocated
                                </span>
                              </div>
                            </div>

                            {/* Progress Bar */}
                            <div className="space-y-2">
                              {(() => {
                                const percentUsed = approval.sla.percentageUsed || 0;
                                const getActiveIndicatorColor = () => {
                                  if (isPaused) return 'bg-gray-500';
                                  if (percentUsed >= 100) return 'bg-red-600';
                                  if (percentUsed >= 75) return 'bg-orange-500';
                                  if (percentUsed >= 50) return 'bg-amber-500';
                                  return 'bg-green-600';
                                };
                                const getActiveTextColor = () => {
                                  if (isPaused) return 'text-gray-600';
                                  if (percentUsed >= 100) return 'text-red-600';
                                  if (percentUsed >= 75) return 'text-orange-600';
                                  if (percentUsed >= 50) return 'text-amber-600';
                                  return 'text-green-600';
                                };
                                return (
                                  <>
                                    <Progress
                                      value={percentUsed}
                                      className="h-3"
                                      indicatorClassName={getActiveIndicatorColor()}
                                    />
                                    <div className="flex items-center justify-between">
                                      <span className={`text-xs font-semibold ${getActiveTextColor()}`}>
                                        Progress: {Math.min(100, percentUsed)}% of TAT used
                                      </span>
                                      <span className="text-xs font-medium text-gray-700">
                                        {approval.sla.remainingText || '0 hours'} remaining
                                      </span>
                                    </div>
                                  </>
                                );
                              })()}

                              {approval.sla.status === 'breached' && (
                                <p className="text-xs font-semibold text-center text-red-600 flex items-center justify-center gap-1.5">
                                  <AlertOctagon className="w-4 h-4" />
                                  Deadline Breached
                                </p>
                              )}
                              {approval.sla.status === 'critical' && (
                                <p className="text-xs font-semibold text-center text-orange-600 flex items-center justify-center gap-1.5">
                                  <AlertTriangle className="w-4 h-4" />
                                  Approaching Deadline
                                </p>
                              )}
                            </div>
                          </div>
                        </div>
                      )}

                      {/* IO Organization Details (Department Lead Approval) - Show when step is approved and has IO details */}
                      {(() => {
                        // Check if this is Department Lead Approval step by step title or levelName (handles step shifts)
                        // Use levelName from the original step data if available, otherwise check title
                        const stepLevelName = (step as any).levelName || (step as any).level_name;
                        const isDeptLeadStep =
                          (stepLevelName && stepLevelName.toLowerCase().includes('department lead')) ||
                          (step.title && step.title.toLowerCase().includes('department lead'));
                        // Only show when step is approved and has IO details.
                        // Hide this section for dealer users.
                        return isDeptLeadStep && !isDealer && step.status === 'approved' && step.ioDetails && step.ioDetails.ioNumber && (
                          <div className="mt-3 p-3 bg-blue-50 rounded-lg border border-blue-200">
                            <div className="flex items-center gap-2 mb-2">
                              <Receipt className="w-4 h-4 text-blue-600" />
                              <p className="text-xs font-semibold text-blue-900 uppercase tracking-wide">
                                IO Organisation Details
                              </p>
                            </div>
                            <div className="space-y-1.5">
                              <div className="flex items-center justify-between">
                                <span className="text-xs text-gray-600">IO Number:</span>
                                <span className="text-sm font-semibold text-gray-900">
                                  {step.ioDetails.ioNumber}
                                </span>
                              </div>
                              {step.ioDetails.blockedAmount !== undefined && step.ioDetails.blockedAmount > 0 && (
                                <div className="flex items-center justify-between pt-1.5 border-t border-blue-100">
                                  <span className="text-xs text-gray-600">Blocked Amount:</span>
                                  <span className="text-sm font-bold text-green-700">
                                    ₹{step.ioDetails.blockedAmount.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                                  </span>
                                </div>
                              )}
                              {step.ioDetails.remainingBalance !== undefined && step.ioDetails.remainingBalance !== null && (
                                <div className="flex items-center justify-between pt-1.5 border-t border-blue-100">
                                  <span className="text-xs text-gray-600">Remaining Balance:</span>
                                  <span className="text-sm font-semibold text-blue-700">
                                    ₹{step.ioDetails.remainingBalance.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                                  </span>
                                </div>
                              )}
                              <div className="pt-1.5 border-t border-blue-100 text-xs text-gray-500">
                                Organised by {step.ioDetails.organizedBy || step.approver || 'N/A'} on{' '}
                                {step.ioDetails.organizedAt
                                  ? formatDateSafe(step.ioDetails.organizedAt)
                                  : (step.approvedAt ? formatDateSafe(step.approvedAt) : 'N/A')
                                }
                              </div>
                            </div>
                          </div>
                        );
                      })()}

                      {/* DMS Processing Details (Step 6) */}
                      {step.step === 6 && step.dmsDetails && step.dmsDetails.dmsNumber && (
                        <div className="mt-3 p-3 bg-purple-50 rounded-lg border border-purple-200">
                          <div className="flex items-center gap-2 mb-2">
                            <Activity className="w-4 h-4 text-purple-600" />
                            <p className="text-xs font-semibold text-purple-900 uppercase tracking-wide">
                              E-Invoice & Settlement Details
                            </p>
                          </div>
                          <div className="space-y-1.5">
                            <div className="flex items-center justify-between">
                              <span className="text-xs text-gray-600">Settlement ID:</span>
                              <span className="text-sm font-semibold text-gray-900">
                                {step.dmsDetails.dmsNumber}
                              </span>
                            </div>
                            {step.dmsDetails.dmsRemarks && (
                              <div className="pt-1.5 border-t border-purple-100">
                                <p className="text-xs text-gray-600 mb-1">Settlement Remarks:</p>
                                <p className="text-sm text-gray-900">{step.dmsDetails.dmsRemarks}</p>
                              </div>
                            )}
                            {step.dmsDetails.pushedAt && (
                              <div className="pt-1.5 border-t border-purple-100 text-xs text-gray-500">
                                Initiated by {step.dmsDetails.pushedBy} on{' '}
                                {formatDateSafe(step.dmsDetails.pushedAt)}
                              </div>
                            )}
                          </div>
                        </div>
                      )}

                      {/* Action Buttons */}
                      {/* Only show action buttons if:
                        1. Step is active (pending/in_progress and matches currentStep)
                        2. AND current user is the approver for this step (or is dealer for dealer steps) */}
                      {(() => {
                        // Find the step level from approvalFlow to verify user is the approver
                        const stepLevel = approvalFlow.find((l: any) => (l.step || l.levelNumber || l.level_number) === step.step);
                        const stepApproverEmail = (stepLevel?.approverEmail || '').toLowerCase();
                        const isUserApproverForThisStep = stepApproverEmail && userEmail === stepApproverEmail;

                        // For dealer steps (1 and 5), also check if user is dealer
                        const isDealerStep = step.step === 1 ||
                          (stepLevel?.levelName && stepLevel.levelName.toLowerCase().includes('dealer'));
                        const isUserAuthorized = isUserApproverForThisStep || (isDealerStep && isDealer);

                        // Step must be active AND user must be authorized AND NOT a spectator
                        return isActive && isUserAuthorized && !isSpectator;
                      })() && (
                          <div className="mt-4 flex gap-2">
                            {/* Step 1: Submit Proposal Button - Only for dealer or step 1 approver */}
                            {(() => {
                              // Check if this is Step 1 (Dealer Proposal Submission)
                              // Use levelName match or fallback to step 1
                              const levelName = (stepLevel?.levelName || step.title || '').toLowerCase();
                              const isProposalStep = step.step === 1 ||
                                levelName.includes('proposal') ||
                                levelName.includes('submission');

                              return isProposalStep && (isDealer || isStep1Approver);
                            })() && (
                                <Button
                                  className="bg-purple-600 hover:bg-purple-700"
                                  onClick={() => {
                                    setShowProposalModal(true);
                                  }}
                                >
                                  <Upload className="w-4 h-4 mr-2" />
                                  Submit Proposal
                                </Button>
                              )}

                            {/* Step 2 (or shifted step): Review Request - Only for initiator or step approver */}
                            {/* Use initiatorStepNumber to handle cases where approvers are added between steps */}
                            {/* Step 2 (or shifted step): Review Request - Only for initiator or step approver */}
                            {/* Use initiatorStepNumber to handle cases where approvers are added between steps */}
                            {/* Step 2 (or shifted step): Review Request - Only for initiator or step approver */}
                            {(() => {
                              // Check if this is the Requestor Evaluation step
                              const levelName = (stepLevel?.levelName || step.title || '').toLowerCase();
                              const isEvaluationStep = levelName.includes('requestor evaluation') ||
                                levelName.includes('confirmation') ||
                                step.step === initiatorStepNumber; // Fallback

                              return isEvaluationStep && (isInitiator || isStep2Approver);
                            })() && (
                                <Button
                                  className="bg-blue-600 hover:bg-blue-700"
                                  onClick={() => {
                                    setShowApprovalModal(true);
                                  }}
                                >
                                  <CheckCircle className="w-4 h-4 mr-2" />
                                  Review Request
                                </Button>
                              )}

                            {/* Initiator Action Step: Show action buttons (REVISE, REOPEN) - Direct actions, no modal */}
                            {(() => {
                              // Find the step level from approvalFlow
                              const stepLevelForInitiator = approvalFlow.find((l: any) => (l.step || l.levelNumber || l.level_number) === step.step);
                              const stepLevelName = (stepLevelForInitiator?.levelName || step.title || '').toLowerCase();
                              const isInitiatorActionStep = stepLevelName.includes('initiator action');
                              const isUserInitiator = isInitiator || (userEmail === initiatorEmail);

                              if (!isInitiatorActionStep || !isUserInitiator) return null;

                              const handleDirectAction = async (action: 'REVISE' | 'REOPEN') => {
                                try {
                                  if (!request?.id && !request?.requestId) {
                                    throw new Error('Request ID not found');
                                  }
                                  const requestId = request.requestId || request.id;

                                  // Call action directly without modal - comments are optional
                                  await handleInitiatorAction(requestId, action, { reason: '' });
                                  toast.success(`Action "${action === 'REVISE' ? 'Revision Requested' : 'Request Reopened'}" performed successfully`);
                                  handleRefresh();
                                } catch (error: any) {
                                  console.error('Failed to perform initiator action:', error);
                                  const errorMessage = error?.response?.data?.message || error?.message || 'Failed to perform action';
                                  toast.error(errorMessage);
                                }
                              };

                              return (
                                <div className="flex flex-wrap gap-2">
                                  <Button
                                    variant="outline"
                                    className="border-orange-500 text-orange-600 hover:bg-orange-50"
                                    onClick={() => handleDirectAction('REVISE')}
                                  >
                                    <RefreshCw className="w-4 h-4 mr-2" />
                                    Request Re-quotation
                                  </Button>
                                  <Button
                                    variant="outline"
                                    className="border-blue-500 text-blue-600 hover:bg-blue-50"
                                    onClick={() => handleDirectAction('REOPEN')}
                                  >
                                    <RotateCw className="w-4 h-4 mr-2" />
                                    Reopen
                                  </Button>
                                </div>
                              );
                            })()}

                            {/* Department Lead Step: Approve and Organise IO - Find dynamically by levelName */}
                            {(() => {
                              // Find Department Lead step dynamically (handles step shifts)
                              const deptLeadStepLevel = approvalFlow.find((l: any) => {
                                const levelName = (l.levelName || '').toLowerCase();
                                return levelName.includes('department lead');
                              });

                              // Check if this is the Department Lead step
                              const isDeptLeadStep = deptLeadStepLevel &&
                                (step.step === (deptLeadStepLevel.step || deptLeadStepLevel.levelNumber || deptLeadStepLevel.level_number));

                              if (!isDeptLeadStep) return null;

                              // Check if user is the Department Lead approver
                              const deptLeadApproverEmail = (deptLeadStepLevel?.approverEmail || '').toLowerCase();
                              const isDeptLeadApprover = deptLeadApproverEmail && userEmail === deptLeadApproverEmail;

                              if (!(isDeptLeadApprover || isStep3Approver || isCurrentApprover)) return null;

                              // Check if IO number is available (same way as IO tab and modal)
                              const internalOrder = request?.internalOrder || request?.internal_order;
                              const ioNumber = internalOrder?.ioNumber || internalOrder?.io_number || request?.ioNumber || '';
                              const hasIONumber = ioNumber && ioNumber.trim() !== '';

                              return (
                                <div className="space-y-1">
                                  <Button
                                    className="bg-green-600 hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed"
                                    onClick={() => {
                                      setShowIOApprovalModal(true);
                                    }}
                                    disabled={!hasIONumber}
                                  >
                                    <CheckCircle className="w-4 h-4 mr-2" />
                                    Review and Approve
                                  </Button>
                                  {!hasIONumber && (
                                    <p className="text-xs text-amber-600">
                                      Please add an IO number in the IO tab before approving this step.
                                    </p>
                                  )}
                                </div>
                              );
                            })()}

                            {/* Step 5 (or shifted step): Upload Completion Documents - Only for dealer */}
                            {/* Check if dealer is the approver for this step (handles step shifts) */}
                            {(() => {
                              // Find the step level from approvalFlow to verify dealer is the approver
                              const stepLevel = approvalFlow.find((l: any) => (l.step || l.levelNumber || l.level_number) === step.step);
                              const stepApproverEmail = (stepLevel?.approverEmail || '').toLowerCase();
                              // Check if dealer is the approver for this step
                              const isDealerForThisStep = isDealer && stepApproverEmail === dealerEmail;
                              // Check if this is the Dealer Completion Documents step
                              // by checking if the levelName contains "Dealer Completion" or "Completion Documents"
                              const levelName = (stepLevel?.levelName || step.title || '').toLowerCase();
                              const isDealerCompletionStep = levelName.includes('dealer completion') ||
                                levelName.includes('completion documents');
                              return isDealerForThisStep && isDealerCompletionStep;
                            })() && (
                                <Button
                                  className="bg-purple-600 hover:bg-purple-700"
                                  onClick={() => {
                                    setShowCompletionModal(true);
                                  }}
                                >
                                  <Upload className="w-4 h-4 mr-2" />
                                  Upload Completion Docs
                                </Button>
                              )}

                            {/* Requestor Claim Approval: Push to DMS - Find dynamically by levelName (handles step shifts) */}
                            {(() => {
                              // Find Requestor Claim Approval step dynamically (handles step shifts)
                              const requestorClaimStepLevel = approvalFlow.find((l: any) => {
                                const levelName = (l.levelName || '').toLowerCase();
                                return levelName.includes('requestor claim') || levelName.includes('requestor - claim');
                              });

                              // Check if this is the Requestor Claim Approval step
                              const isRequestorClaimStep = requestorClaimStepLevel &&
                                (step.step === (requestorClaimStepLevel.step || requestorClaimStepLevel.levelNumber || requestorClaimStepLevel.level_number));

                              if (!isRequestorClaimStep) return null;

                              // Check if user is the initiator or the Requestor Claim Approval approver
                              const requestorClaimApproverEmail = (requestorClaimStepLevel?.approverEmail || '').toLowerCase();
                              const isRequestorClaimApprover = requestorClaimApproverEmail && userEmail === requestorClaimApproverEmail;

                              if (!(isInitiator || isRequestorClaimApprover)) return null;

                              return (
                                <Button
                                  className="bg-indigo-600 hover:bg-indigo-700"
                                  onClick={() => {
                                    setShowDMSPushModal(true);
                                  }}
                                >
                                  <Activity className="w-4 h-4 mr-2" />
                                  Generate E-Invoice & Sync
                                </Button>
                              );
                            })()}

                            {/* Step 8: View & Send Credit Note - Only for finance approver or step 8 approver */}
                            {(() => {
                              const levelName = (stepLevel?.levelName || step.title || '').toLowerCase();
                              // Check for "Credit Note" or "SAP" in level name, or fallback to step 8 if it's the last step
                              const isCreditNoteStep = levelName.includes('credit note') ||
                                levelName.includes('sap') ||
                                (step.step === 8 && !levelName.includes('additional'));

                              const stepApproverEmail = (stepLevel?.approverEmail || '').toLowerCase();
                              const isStepApprover = stepApproverEmail && userEmail === stepApproverEmail;
                              // Also check if user has finance role
                              const userRole = (user as any)?.role?.toUpperCase() || '';
                              const isFinanceUser = userRole === 'FINANCE' || userRole === 'ADMIN';

                              return isCreditNoteStep && (isStepApprover || isFinanceUser);
                            })() && (
                                <Button
                                  className="bg-green-600 hover:bg-green-700"
                                  onClick={() => {
                                    setShowCreditNoteModal(true);
                                  }}
                                >
                                  <Receipt className="w-4 h-4 mr-2" />
                                  View & Send Credit Note
                                </Button>
                              )}

                            {/* Additional Approvers: Show approve/reject buttons for steps that don't have specific workflow actions */}
                            {(() => {
                              // Check if this is an additional approver step (not one of the fixed workflow steps)
                              const stepLevel = approvalFlow.find((l: any) => (l.step || l.levelNumber || l.level_number) === step.step);
                              const levelName = (stepLevel?.levelName || step.title || '').toLowerCase();
                              const isAdditionalApprover = levelName.includes('additional approver');

                              // Check if this step doesn't have any of the specific workflow action buttons above
                              // Check if this step doesn't have any of the specific workflow action buttons above
                              const hasSpecificWorkflowAction =
                                // Proposal
                                (step.step === 1 || levelName.includes('proposal') || levelName.includes('submission')) ||
                                // Evaluation
                                (levelName.includes('requestor evaluation') || levelName.includes('confirmation')) ||
                                // Dept Lead
                                levelName.includes('department lead') ||
                                // Dealer Completion
                                (levelName.includes('dealer completion') || levelName.includes('completion documents')) ||
                                // Requestor Claim
                                (levelName.includes('requestor claim') || levelName.includes('requestor - claim')) ||
                                // Credit Note
                                (levelName.includes('credit note') || levelName.includes('sap'));

                              // Show "Review Request" button for additional approvers or steps without specific workflow actions
                              // Similar to the requestor approval step
                              if (isAdditionalApprover || !hasSpecificWorkflowAction) {
                                const levelId = stepLevel?.levelId || stepLevel?.level_id;

                                // Show review modal with both approve and reject options
                                if (levelId) {
                                  const levelName = stepLevel?.levelName || stepLevel?.level_name || step.title || 'Approval Level';
                                  const approverName = stepLevel?.approverName || stepLevel?.approver_name || step.approver || 'Approver';
                                  return (
                                    <Button
                                      className="bg-blue-600 hover:bg-blue-700"
                                      onClick={() => {
                                        setSelectedLevelForReview({ levelId, levelName, approverName });
                                        setShowAdditionalApproverReviewModal(true);
                                      }}
                                    >
                                      <CheckCircle className="w-4 h-4 mr-2" />
                                      Review Request
                                    </Button>
                                  );
                                }

                                // Fallback: Direct API call if levelId not available (shouldn't happen in normal flow)
                                return (
                                  <>
                                    <Button
                                      className="bg-green-600 hover:bg-green-700"
                                      onClick={async () => {
                                        try {
                                          if (!request?.id && !request?.requestId) {
                                            throw new Error('Request ID not found');
                                          }
                                          const requestId = request.id || request.requestId;
                                          if (!levelId) {
                                            toast.error('Approval level not found');
                                            return;
                                          }
                                          await approveLevel(requestId, levelId, '');
                                          toast.success('Request approved successfully');
                                          handleRefresh();
                                        } catch (error: any) {
                                          console.error('Failed to approve:', error);
                                          const errorMessage = error?.response?.data?.message || error?.message || 'Failed to approve request. Please try again.';
                                          toast.error(errorMessage);
                                        }
                                      }}
                                    >
                                      <CheckCircle className="w-4 h-4 mr-2" />
                                      Approve
                                    </Button>
                                    <Button
                                      variant="destructive"
                                      onClick={async () => {
                                        try {
                                          if (!request?.id && !request?.requestId) {
                                            throw new Error('Request ID not found');
                                          }
                                          const requestId = request.id || request.requestId;
                                          if (!levelId) {
                                            toast.error('Approval level not found');
                                            return;
                                          }
                                          const comments = prompt('Please provide a reason for rejection:');
                                          if (comments === null) return; // User cancelled
                                          await rejectLevel(requestId, levelId, 'Request rejected', comments);
                                          toast.success('Request rejected successfully');
                                          handleRefresh();
                                        } catch (error: any) {
                                          console.error('Failed to reject:', error);
                                          const errorMessage = error?.response?.data?.message || error?.message || 'Failed to reject request. Please try again.';
                                          toast.error(errorMessage);
                                        }
                                      }}
                                    >
                                      <XCircle className="w-4 h-4 mr-2" />
                                      Reject
                                    </Button>
                                  </>
                                );
                              }
                              return null;
                            })()}
                          </div>
                        )}

                      {/* Approved Date */}
                      {step.approvedAt && (
                        <p className="text-xs text-gray-500 mt-2">
                          Approved on {formatDateSafe(step.approvedAt)}
                        </p>
                      )}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </CardContent>
      </Card>

      {/* Dealer Proposal Submission Modal */}
      <DealerProposalSubmissionModal
        isOpen={showProposalModal}
        onClose={() => setShowProposalModal(false)}
        onSubmit={handleProposalSubmit}
        dealerName={dealerName}
        dealerGSTIN={dealerGSTIN}
        activityName={activityName}
        defaultGstRate={request?.claimDetails?.defaultGstRate}
        requestId={request?.id || request?.requestId}
        previousProposalData={versionHistory?.find(v => v.snapshotType === 'PROPOSAL')?.snapshotData}
        documentPolicy={documentPolicy}
        taxationType={request?.claimDetails?.taxationType}
        totalBlockedAmount={(request?.internalOrders || []).reduce((sum: number, io: any) => sum + (Number(io.ioBlockedAmount || io.io_blocked_amount || io.blockedAmount || 0)), 0)}
      />

      {/* Initiator Proposal Approval Modal */}
      <InitiatorProposalApprovalModal
        isOpen={showApprovalModal}
        onClose={() => {
          setShowApprovalModal(false);
        }}
        onApprove={handleProposalApprove}
        onReject={handleProposalReject}
        onRequestRevision={handleProposalRevision}
        proposalData={proposalData}
        dealerName={dealerName}
        activityName={activityName}
        requestId={request?.id || request?.requestId}
        request={request}
        previousProposalData={(() => {
          const proposalSnapshots = versionHistory?.filter(v => v.snapshotType === 'PROPOSAL') || [];
          // Since history is sorted descending (most recent first):
          // proposalSnapshots[0] is the current proposal being reviewed
          // proposalSnapshots[1] is the previous proposal (last iteration - 1)
          return proposalSnapshots.length > 1 ? proposalSnapshots[1].snapshotData : null;
        })()}
        taxationType={request?.claimDetails?.taxationType}
      />

      {/* Dept Lead IO Approval Modal */}
      <DeptLeadIOApprovalModal
        isOpen={showIOApprovalModal}
        onClose={() => setShowIOApprovalModal(false)}
        onApprove={handleIOApproval}
        onReject={handleIORejection}
        requestTitle={request?.title}
        requestId={request?.id || request?.requestId}
        preFilledIONumber={request?.internalOrder?.ioNumber || request?.internalOrder?.io_number || request?.internal_order?.ioNumber || request?.internal_order?.io_number || undefined}
        preFilledBlockedAmount={request?.internalOrder?.ioBlockedAmount || request?.internalOrder?.io_blocked_amount || request?.internal_order?.ioBlockedAmount || request?.internal_order?.io_blocked_amount || undefined}
        preFilledRemainingBalance={request?.internalOrder?.ioRemainingBalance || request?.internalOrder?.io_remaining_balance || request?.internal_order?.ioRemainingBalance || request?.internal_order?.io_remaining_balance || undefined}
        taxationType={request?.claimDetails?.taxationType}
      />

      {/* Dealer Completion Documents Modal */}
      <DealerCompletionDocumentsModal
        isOpen={showCompletionModal}
        onClose={() => setShowCompletionModal(false)}
        onSubmit={handleCompletionSubmit}
        dealerName={dealerName}
        dealerGSTIN={dealerGSTIN}
        activityName={activityName}
        defaultGstRate={request?.claimDetails?.defaultGstRate}
        requestId={request?.id || request?.requestId}
        documentPolicy={documentPolicy}
        taxationType={request?.claimDetails?.taxationType}
      />

      {/* DMS Push Modal */}
      <DMSPushModal
        isOpen={showDMSPushModal}
        onClose={() => setShowDMSPushModal(false)}
        onPush={handleDMSPush}
        completionDetails={{
          activityCompletionDate: request?.completionDetails?.activityCompletionDate || request?.completionDetails?.activity_completion_date,
          numberOfParticipants: request?.completionDetails?.numberOfParticipants || request?.completionDetails?.number_of_participants,
          closedExpenses: request?.completionExpenses || request?.completion_expenses || request?.completionDetails?.closedExpenses || request?.completionDetails?.closed_expenses,
          totalClosedExpenses: request?.budgetTracking?.closedExpenses || request?.budgetTracking?.closed_expenses || request?.completionDetails?.totalClosedExpenses || request?.completionDetails?.total_closed_expenses,
          completionDescription: request?.completionDetails?.completionDescription || request?.completionDetails?.completion_description,
        }}
        ioDetails={{
          ioNumber: request?.internalOrder?.ioNumber || request?.internalOrder?.io_number || request?.internal_order?.ioNumber || request?.internal_order?.io_number,
          blockedAmount: request?.internalOrder?.ioBlockedAmount || request?.internalOrder?.io_blocked_amount || request?.internal_order?.ioBlockedAmount || request?.internal_order?.io_blocked_amount,
          availableBalance: request?.internalOrder?.ioAvailableBalance || request?.internalOrder?.io_available_balance || request?.internal_order?.ioAvailableBalance || request?.internal_order?.io_available_balance,
          remainingBalance: request?.internalOrder?.ioRemainingBalance || request?.internalOrder?.io_remaining_balance || request?.internal_order?.ioRemainingBalance || request?.internal_order?.io_remaining_balance,
        }}
        completionDocuments={completionDocumentsData}
        requestTitle={request?.title}
        requestNumber={request?.requestNumber || request?.request_number || request?.id}
        taxationType={request?.claimDetails?.taxationType}
        onReQuotation={handleClaimReQuotation}
      />

      {/* Credit Note from SAP Modal (Step 8) */}
      <CreditNoteSAPModal
        isOpen={showCreditNoteModal}
        onClose={() => setShowCreditNoteModal(false)}
        taxationType={request?.claimDetails?.taxationType}
        onDownload={async () => {
          toast.info('Download functionality will be implemented');
        }}
        onSendToDealer={async () => {
          try {
            const requestId = request?.requestId || request?.id;
            if (!requestId) {
              toast.error('Request ID not found');
              return;
            }

            await sendCreditNoteToDealer(requestId);

            toast.success('Credit note sent to dealer successfully. Step 8 has been approved.');

            // Refresh the request details to show updated status
            if (onRefresh) {
              onRefresh();
            }
          } catch (error: any) {
            console.error('Failed to send credit note to dealer:', error);
            const errorMessage = error?.response?.data?.message || error?.message || 'Failed to send credit note to dealer';
            toast.error(errorMessage);
          }
        }}
        creditNoteData={{
          creditNoteNumber: (request as any)?.creditNote?.creditNoteNumber ||
            (request as any)?.creditNote?.credit_note_number ||
            (request as any)?.claimDetails?.creditNote?.creditNoteNumber ||
            (request as any)?.claimDetails?.creditNoteNumber ||
            (request as any)?.claimDetails?.credit_note_number,
          creditNoteDate: (request as any)?.creditNote?.creditNoteDate ||
            (request as any)?.creditNote?.credit_note_date ||
            (request as any)?.claimDetails?.creditNote?.creditNoteDate ||
            (request as any)?.claimDetails?.creditNoteDate ||
            (request as any)?.claimDetails?.credit_note_date,
          creditNoteAmount: (request as any)?.creditNote?.creditNoteAmount ?
            Number((request as any)?.creditNote?.creditNoteAmount) :
            ((request as any)?.creditNote?.credit_note_amount ?
              Number((request as any)?.creditNote?.credit_note_amount) :
              ((request as any)?.claimDetails?.creditNote?.creditNoteAmount ?
                Number((request as any)?.claimDetails?.creditNote?.creditNoteAmount) :
                ((request as any)?.claimDetails?.creditNoteAmount ?
                  Number((request as any)?.claimDetails?.creditNoteAmount) :
                  ((request as any)?.claimDetails?.credit_note_amount ?
                    Number((request as any)?.claimDetails?.credit_note_amount) : undefined)))),
          transactionNo: (request as any)?.creditNote?.transactionNo || (request as any)?.creditNote?.transaction_no,
          tdsAmount: (request as any)?.creditNote?.tdsAmount || (request as any)?.creditNote?.tds_amount,
          creditAmount: (request as any)?.creditNote?.creditAmount || (request as any)?.creditNote?.credit_amount,
          items: (request as any)?.creditNote?.items || [],
          status: (request as any)?.creditNote?.status ||
            (request as any)?.claimDetails?.creditNote?.status ||
            ((request as any)?.creditNote?.creditNoteNumber ? 'CONFIRMED' : 'PENDING'),
        }}
        dealerInfo={{
          dealerName: (request as any)?.claimDetails?.dealerName || (request as any)?.claimDetails?.dealer_name,
          dealerCode: (request as any)?.claimDetails?.dealerCode || (request as any)?.claimDetails?.dealer_code,
          dealerEmail: (request as any)?.claimDetails?.dealerEmail || (request as any)?.claimDetails?.dealer_email,
        }}
        activityName={(request as any)?.claimDetails?.activityName || (request as any)?.claimDetails?.activity_name}
        requestNumber={request?.requestNumber || request?.id}
        requestId={request?.requestId || request?.id}
        dueDate={request?.dueDate}
      />

      {/* Email Notification Template Modal */}
      <EmailNotificationTemplateModal
        isOpen={showEmailTemplateModal}
        onClose={() => {
          setShowEmailTemplateModal(false);
          setSelectedStepForEmail(null);
        }}
        stepNumber={selectedStepForEmail?.stepNumber || 4}
        stepName={selectedStepForEmail?.stepName || 'Activity Creation'}
        requestNumber={request?.requestNumber || request?.id || request?.request_number}
        recipientEmail={`system@${import.meta.env.VITE_EMAIL_DOMAIN}`}
      />

      {/* Additional Approver Review Modal */}
      {selectedLevelForReview && (
        <AdditionalApproverReviewModal
          isOpen={showAdditionalApproverReviewModal}
          onClose={() => {
            setShowAdditionalApproverReviewModal(false);
            setSelectedLevelForReview(null);
          }}
          onApprove={async (comments: string) => {
            try {
              if (!request?.id && !request?.requestId) {
                throw new Error('Request ID not found');
              }
              const requestId = request.id || request.requestId;
              const levelId = selectedLevelForReview.levelId;
              if (!levelId) {
                toast.error('Approval level not found');
                return;
              }
              await approveLevel(requestId, levelId, comments);
              toast.success('Request approved successfully');
              handleRefresh();
              setShowAdditionalApproverReviewModal(false);
              setSelectedLevelForReview(null);
            } catch (error: any) {
              console.error('Failed to approve:', error);
              const errorMessage = error?.response?.data?.message || error?.message || 'Failed to approve request. Please try again.';
              toast.error(errorMessage);
              throw error;
            }
          }}
          onReject={async (comments: string) => {
            try {
              if (!request?.id && !request?.requestId) {
                throw new Error('Request ID not found');
              }
              const requestId = request.id || request.requestId;
              const levelId = selectedLevelForReview.levelId;
              if (!levelId) {
                toast.error('Approval level not found');
                return;
              }
              await rejectLevel(requestId, levelId, 'Request rejected', comments);
              toast.success('Request rejected successfully');
              handleRefresh();
              setShowAdditionalApproverReviewModal(false);
              setSelectedLevelForReview(null);
            } catch (error: any) {
              console.error('Failed to reject:', error);
              const errorMessage = error?.response?.data?.message || error?.message || 'Failed to reject request. Please try again.';
              toast.error(errorMessage);
              throw error;
            }
          }}
          requestTitle={request?.title || 'Request'}
          requestDescription={request?.description || ''}
          requestId={request?.id || request?.requestId}
          levelName={selectedLevelForReview.levelName}
          approverName={selectedLevelForReview.approverName}
        />
      )}

      {/* Initiator Action Modal - Removed, actions are now direct buttons in step card */}

      {/* Version History Section */}
      {versionHistory && versionHistory.length > 0 && (
        <Card className="mt-6 border-amber-100 bg-amber-50/30">
          <CardHeader className="pb-3">
            <div className="flex items-center justify-between">
              <CardTitle className="text-sm font-bold flex items-center gap-2 text-amber-900">
                <Activity className="w-4 h-4" />
                Revision History & Audit Trail
              </CardTitle>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => setShowHistory(!showHistory)}
                className="text-amber-700 hover:text-amber-800 hover:bg-amber-100"
              >
                {showHistory ? 'Hide History' : 'View History'}
              </Button>
            </div>
            <CardDescription className="text-xs text-amber-700">
              Records of all revisions and actions taken on this request
            </CardDescription>
          </CardHeader>
          {showHistory && (
            <CardContent>
              <div className="space-y-4">
                {versionHistory.map((item, idx) => (
                  <div key={item.historyId || idx} className="relative pl-6 pb-4 border-l-2 border-amber-200 last:border-0 last:pb-0">
                    <div className="absolute left-[-9px] top-0 w-4 h-4 rounded-full bg-amber-500 border-2 border-white shadow-sm" />
                    <div className="flex flex-col gap-1">
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-2">
                          <span className="text-xs font-bold text-amber-900">
                            Version {item.version}
                          </span>
                          {item.snapshotType && (
                            <Badge className="bg-blue-100 text-blue-700 text-[9px] px-1.5 py-0">
                              {item.snapshotType}
                            </Badge>
                          )}
                          {item.levelNumber && (
                            <Badge className="bg-gray-100 text-gray-600 text-[9px] px-1.5 py-0">
                              Step {item.levelNumber}
                            </Badge>
                          )}
                        </div>
                        <span className="text-[10px] text-amber-600 font-medium bg-amber-100 px-2 py-0.5 rounded-full">
                          {formatDateSafe(item.createdAt)}
                        </span>
                      </div>
                      <p className="text-xs font-medium text-gray-800">
                        {item.changeReason || 'Version Update'}
                      </p>
                      <div className="flex items-center gap-1.5 mt-1">
                        <div className="w-4 h-4 rounded-full bg-blue-100 flex items-center justify-center">
                          <span className="text-[8px] font-bold text-blue-600">
                            {item.changer?.displayName?.charAt(0) || 'U'}
                          </span>
                        </div>
                        <span className="text-xs text-gray-500">
                          By {item.changer?.displayName || item.changer?.email || 'Unknown User'}
                        </span>
                      </div>
                      {/* Show snapshot details based on type - JSONB structure */}
                      {item.snapshotType === 'PROPOSAL' && item.snapshotData && (
                        <div className="mt-2 p-2 bg-white rounded border border-amber-200 text-[10px]">
                          <p className="font-semibold text-gray-700 mb-1">Proposal:</p>
                          {item.snapshotData.documentUrl && (
                            <div className="flex items-center gap-2 mb-1">
                              <Button
                                variant="link"
                                size="sm"
                                className="h-auto p-0 text-blue-600 hover:text-blue-700 font-small flex items-center gap-1"
                                onClick={() => setViewSnapshot({
                                  data: item.snapshotData,
                                  type: 'PROPOSAL',
                                  title: `Historical Proposal (Version ${item.version})`
                                })}
                              >
                                View Details
                                <Eye className="w-2 h-2" />
                              </Button>
                            </div>
                          )}
                          <p className="text-gray-600">Budget: ₹{Number(item.snapshotData.totalBudget || 0).toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</p>
                          {item.snapshotData.comments && (
                            <p className="text-gray-600 mt-1">Comments: {item.snapshotData.comments.substring(0, 80)}{item.snapshotData.comments.length > 80 ? '...' : ''}</p>
                          )}
                        </div>
                      )}
                      {item.snapshotType === 'COMPLETION' && item.snapshotData && (
                        <div className="mt-2 p-2 bg-white rounded border border-amber-200 text-[10px]">
                          <p className="font-semibold text-gray-700 mb-1">Completion:</p>
                          {item.snapshotData.documentUrl && (
                            <div className="flex items-center gap-2 mb-1">
                              <Button
                                variant="link"
                                size="sm"
                                className="h-auto p-0 text-blue-600 hover:text-blue-700 font-medium flex items-center gap-1"
                                onClick={() => setViewSnapshot({
                                  data: item.snapshotData,
                                  type: 'COMPLETION',
                                  title: `Historical Completion (Version ${item.version})`
                                })}
                              >
                                View Details
                                <Eye className="w-3 h-3" />
                              </Button>
                            </div>
                          )}
                          <p className="text-gray-600">Total Expenses: ₹{Number(item.snapshotData.totalExpenses || 0).toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</p>
                          {item.snapshotData.comments && (
                            <p className="text-gray-600 mt-1">Comments: {item.snapshotData.comments.substring(0, 80)}{item.snapshotData.comments.length > 80 ? '...' : ''}</p>
                          )}
                        </div>
                      )}
                      {item.snapshotType === 'INTERNAL_ORDER' && item.snapshotData && (
                        <div className="mt-2 p-2 bg-white rounded border border-amber-200 text-[10px]">
                          <p className="font-semibold text-gray-700 mb-1">IO Block:</p>
                          <p className="text-gray-600">IO Number: {item.snapshotData.ioNumber || 'N/A'}</p>
                          <p className="text-gray-600">Blocked: ₹{Number(item.snapshotData.blockedAmount || 0).toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</p>
                          {item.snapshotData.sapDocumentNumber && (
                            <p className="text-gray-600">SAP Doc: {item.snapshotData.sapDocumentNumber}</p>
                          )}
                        </div>
                      )}
                      {item.snapshotType === 'APPROVE' && item.snapshotData && (
                        <div className="mt-2 p-2 bg-white rounded border border-amber-200 text-[10px]">
                          <p className="font-semibold text-gray-700 mb-1">
                            {item.snapshotData.action === 'APPROVE' ? 'Approval' : 'Rejection'}:
                          </p>
                          <p className="text-gray-600">By: {item.snapshotData.approverName || item.snapshotData.approverEmail || 'Unknown'}</p>
                          {item.snapshotData.levelName && (
                            <p className="text-gray-600">Level: {item.snapshotData.levelName}</p>
                          )}
                          {item.snapshotData.comments && (
                            <p className="text-gray-600 mt-1">Comments: {item.snapshotData.comments.substring(0, 80)}{item.snapshotData.comments.length > 80 ? '...' : ''}</p>
                          )}
                          {item.snapshotData.rejectionReason && (
                            <p className="text-red-600 mt-1">Rejection Reason: {item.snapshotData.rejectionReason.substring(0, 80)}{item.snapshotData.rejectionReason.length > 80 ? '...' : ''}</p>
                          )}
                        </div>
                      )}
                      {item.snapshotType === 'WORKFLOW' && item.snapshotData && (
                        <div className="mt-2 p-2 bg-white rounded border border-amber-200 text-[10px]">
                          <p className="font-semibold text-gray-700 mb-1">Workflow:</p>
                          <p className="text-gray-600">Status: {item.snapshotData.status || 'N/A'}</p>
                          {item.snapshotData.currentLevel && (
                            <p className="text-gray-600">Current Level: {item.snapshotData.currentLevel}</p>
                          )}
                        </div>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          )}
        </Card>
      )}

      <SnapshotDetailsModal
        isOpen={!!viewSnapshot}
        onClose={() => setViewSnapshot(null)}
        snapshot={viewSnapshot?.data}
        type={viewSnapshot?.type || 'PROPOSAL'}
        title={viewSnapshot?.title}
      />

      {/* Invoice PDF Viewer Modal */}
      {showInvoicePdfModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center">
          {/* Backdrop */}
          <div className="absolute inset-0 bg-black/60" onClick={handleCloseInvoicePdf} />
          {/* Modal */}
          <div className="relative w-[95vw] max-w-5xl h-[90vh] bg-white rounded-xl shadow-2xl flex flex-col overflow-hidden">
            {/* Header */}
            <div className="flex items-center justify-between px-5 py-3 border-b bg-gray-50">
              <div className="flex items-center gap-2">
                <Receipt className="w-5 h-5 text-amber-600" />
                <h3 className="font-semibold text-gray-900">Invoice Preview</h3>
                <Badge className="bg-amber-100 text-amber-800 text-xs">{request.requestNumber}</Badge>
              </div>
              <div className="flex items-center gap-2">
                {invoicePdfUrl && (
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={handleDownloadInvoicePdf}
                    className="gap-1.5 text-xs"
                  >
                    <Download className="w-3.5 h-3.5" />
                    Download
                  </Button>
                )}
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={handleCloseInvoicePdf}
                  className="h-8 w-8 hover:bg-gray-200"
                >
                  <X className="w-4 h-4" />
                </Button>
              </div>
            </div>
            {/* Body */}
            <div className="flex-1 overflow-hidden">
              {invoicePdfLoading ? (
                <div className="flex flex-col items-center justify-center h-full gap-3">
                  <Loader2 className="w-8 h-8 text-amber-600 animate-spin" />
                  <p className="text-sm text-gray-500">Loading invoice...</p>
                </div>
              ) : invoicePdfUrl ? (
                <iframe
                  src={invoicePdfUrl}
                  className="w-full h-full border-0"
                  title="Invoice PDF Preview"
                />
              ) : (
                <div className="flex items-center justify-center h-full">
                  <p className="text-sm text-gray-500">Failed to load invoice</p>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </>
  );
}
