import { Component, OnInit, OnDestroy, ViewChild, ElementRef, AfterViewChecked } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ChatService, ChatUser, Conversation, Message } from '../../services/chat.service';
import { NotificationService } from '../../services/notification.service';
import { UserService, UserInfo } from '../../services/user.service';
import { CallService } from '../../services/call.service';
import { LoggerService } from '../../services/logger.service';
import { CallComponent } from '../call/call.component';
import { Subscription, debounceTime, distinctUntilChanged, Subject } from 'rxjs';
import { ModalService } from '../../services/modal.service';

@Component({
  selector: 'app-chat',
  standalone: true,
  imports: [CommonModule, FormsModule, CallComponent],
  templateUrl: './chat.component.html',
  styleUrl: './chat.component.scss'
})
export class ChatComponent implements OnInit, OnDestroy, AfterViewChecked {
  @ViewChild('messagesContainer') private messagesContainer!: ElementRef;
  
  conversations: Conversation[] = [];
  selectedConversation: Conversation | null = null;
  messages: Message[] = [];
  newMessage: string = '';
  unreadCount: number = 0;
  isOtherUserTyping: boolean = false;
  typingUserName: string = '';
  private subscriptions: Subscription[] = [];
  private shouldScrollToBottom = false;
  private typingTimeout: any = null;
  private stopTypingTimeout: any = null;
  private lastTypingNotification: number = 0;
  
  // Modal state
  showDeleteModal: boolean = false;
  deleteModalType: 'message' | 'conversation' = 'conversation';
  messageToDelete: Message | null = null;

  currentUserId: string | null = null;
  currentUser: UserInfo | null = null;
  
  // User status
  currentUserStatus: 'ONLINE' | 'OFFLINE' | 'BUSY' = 'ONLINE';
  showStatusMenu: boolean = false;
  
  // Search functionality
  showSearch: boolean = false;
  searchQuery: string = '';
  searchResults: ChatUser[] = [];
  isSearching: boolean = false;
  private searchSubject = new Subject<string>();

  // Blocked users functionality
  showBlockedUsers: boolean = false;
  blockedUsers: ChatUser[] = [];
  isLoadingBlockedUsers: boolean = false;
  isUserBlocked: boolean = false;

  // UI state
  showMoreMenu: boolean = false;
  showMessageActions: string | null = null;


  constructor(
    private chatService: ChatService,
    private notificationService: NotificationService,
    public userService: UserService,
    private callService: CallService,
    private modalService: ModalService,
    private logger: LoggerService
  ) {}

  async ngOnInit(): Promise<void> {
    this.currentUser = await this.userService.getCurrentUser();
    if (this.currentUser) {
      this.currentUserId = this.currentUser.id;
      // Load current user status from backend or default to ONLINE
      this.currentUserStatus = (this.currentUser.status as 'ONLINE' | 'OFFLINE' | 'BUSY') || 'ONLINE';
    }
    
    // Close status menu when clicking outside
    document.addEventListener('click', (event) => {
      const target = event.target as HTMLElement;
      if (this.showStatusMenu && !target.closest('.status-selector')) {
        this.showStatusMenu = false;
      }
      if (this.showMoreMenu && !target.closest('.more-menu')) {
        this.showMoreMenu = false;
      }
    });
    await this.chatService.connect();
    
    // Setup search debounce
    const searchSub = this.searchSubject.pipe(
      debounceTime(300),
      distinctUntilChanged()
    ).subscribe(query => {
      this.performSearch(query);
    });
    this.subscriptions.push(searchSub);
    
    // Subscribe to new messages
    const messageSub = this.chatService.messages$.subscribe((message: Message) => {
      if (this.selectedConversation && 
          (message.senderId === this.selectedConversation.otherUserId || 
           message.receiverId === this.selectedConversation.otherUserId)) {
        // Remove optimistic message if exists (same content)
        const existingIndex = this.messages.findIndex(m => 
          !m.id && m.content === message.content && m.senderId === this.currentUserId
        );
        if (existingIndex !== -1) {
          this.messages[existingIndex] = message;
        } else {
          this.messages.push(message);
        }
        this.shouldScrollToBottom = true;
      }
      this.refreshConversations();
    });

    // Subscribe to online status updates
    const statusSub = this.chatService.onlineStatus$.subscribe(status => {
      this.logger.debug('Received online status update:', status);
      
      // Update current user's own status if it's their update
      if (status.userId === this.currentUserId && status.status) {
        this.currentUserStatus = status.status as 'ONLINE' | 'OFFLINE' | 'BUSY';
      }
      
      // Update conversation status for other users
      const conversation = this.conversations.find(c => c.otherUserId === status.userId);
      if (conversation) {
        conversation.isOnline = status.isOnline;
        conversation.otherUserStatus = status.status as 'ONLINE' | 'OFFLINE' | 'BUSY';
        conversation.lastSeen = status.lastSeen;
        // Trigger change detection
        this.conversations = [...this.conversations];
      }
      if (this.selectedConversation?.otherUserId === status.userId) {
        this.selectedConversation.isOnline = status.isOnline;
        this.selectedConversation.otherUserStatus = status.status as 'ONLINE' | 'OFFLINE' | 'BUSY';
        this.selectedConversation.lastSeen = status.lastSeen;
        // Trigger change detection for selected conversation
        this.selectedConversation = { ...this.selectedConversation };
      }
    });

    // Subscribe to conversations updates
    const conversationsSub = this.chatService.conversations$.subscribe(conversations => {
      // Deduplicate conversations by otherUserId to prevent duplicate entries
      const uniqueConversations = conversations.reduce((acc, conversation) => {
        const existingIndex = acc.findIndex(c => c.otherUserId === conversation.otherUserId);
        if (existingIndex === -1) {
          acc.push(conversation);
        } else {
          // If duplicate exists, keep the one with more recent lastMessage or higher unreadCount
          const existing = acc[existingIndex];
          if (conversation.lastMessage && (!existing.lastMessage || 
              new Date(conversation.lastMessage.createdAt) > new Date(existing.lastMessage.createdAt))) {
            acc[existingIndex] = conversation;
          } else if (conversation.unreadCount > existing.unreadCount) {
            acc[existingIndex] = conversation;
          } else {
            // Update status if the duplicate has a newer status
            if (conversation.otherUserStatus && (!existing.otherUserStatus || 
                conversation.isOnline !== existing.isOnline)) {
              existing.otherUserStatus = conversation.otherUserStatus;
              existing.isOnline = conversation.isOnline;
              existing.lastSeen = conversation.lastSeen;
            }
          }
        }
        return acc;
      }, [] as Conversation[]);
      
      this.conversations = uniqueConversations;
      this.unreadCount = uniqueConversations.reduce((sum, c) => sum + c.unreadCount, 0);
      
      // Update current user status from conversation data if available
      // This is a workaround - ideally we'd get it from user profile
      // For now, we'll initialize from the first conversation that has status
      if (uniqueConversations.length > 0 && !this.currentUserStatus) {
        // Status will be initialized when user logs in
      }
    });

    // Subscribe to typing notifications
    const typingSub = this.chatService.typing$.subscribe(typingData => {
      if (this.selectedConversation && 
          typingData.userId === this.selectedConversation.otherUserId) {
        this.isOtherUserTyping = typingData.isTyping;
        this.typingUserName = typingData.senderName || this.selectedConversation.otherUserName;
        
        // Auto-hide typing indicator after 3 seconds if no new typing event
        if (typingData.isTyping) {
          if (this.typingTimeout) {
            clearTimeout(this.typingTimeout);
          }
          // Scroll to bottom when typing indicator appears
          this.shouldScrollToBottom = true;
          // Also scroll immediately and after a small delay to ensure typing indicator is visible
          setTimeout(() => this.scrollToBottom(), 100);
          this.typingTimeout = setTimeout(() => {
            this.isOtherUserTyping = false;
          }, 3000);
        } else {
          // Clear timeout if typing stops
          if (this.typingTimeout) {
            clearTimeout(this.typingTimeout);
            this.typingTimeout = null;
          }
        }
      }
    });

    this.subscriptions.push(messageSub, statusSub, conversationsSub, typingSub);
    this.loadConversations();
  }

  ngAfterViewChecked(): void {
    if (this.shouldScrollToBottom) {
      // Use setTimeout to ensure DOM is fully updated before scrolling
      setTimeout(() => {
        this.scrollToBottom();
        this.shouldScrollToBottom = false;
      }, 0);
    }
  }

  ngOnDestroy(): void {
    // Stop typing indicator when component is destroyed
    if (this.selectedConversation) {
      this.chatService.sendTypingNotification(this.selectedConversation.otherUserId, false);
    }
    
    // Clear active conversation in notification service
    this.notificationService.clearActiveConversation();
    
    // Clear typing timeouts
    if (this.typingTimeout) {
      clearTimeout(this.typingTimeout);
      this.typingTimeout = null;
    }
    if (this.stopTypingTimeout) {
      clearTimeout(this.stopTypingTimeout);
      this.stopTypingTimeout = null;
    }
    this.subscriptions.forEach(sub => sub.unsubscribe());
    // Don't disconnect - keep connection alive while app is running
  }

  async loadConversations(): Promise<void> {
    this.conversations = await this.chatService.getConversations();
    this.unreadCount = this.conversations.reduce((sum, c) => sum + c.unreadCount, 0);
  }

  async selectConversation(conversation: Conversation): Promise<void> {
    // Stop any typing indicators from previous conversation
    if (this.selectedConversation) {
      this.chatService.sendTypingNotification(this.selectedConversation.otherUserId, false);
    }
    
    this.selectedConversation = conversation;
    
    // Set active conversation in notification service to prevent notifications when chat is open
    if (conversation.otherUserId) {
      this.notificationService.setActiveConversation(conversation.otherUserId);
    }
    
    this.messages = await this.chatService.getConversation(conversation.otherUserId);
    this.isOtherUserTyping = false; // Reset typing indicator
    await this.chatService.markAsRead(conversation.otherUserId);
    this.shouldScrollToBottom = true;
    
    // Check if user is blocked
    if (conversation.otherUserId) {
      this.isUserBlocked = await this.chatService.isBlocked(conversation.otherUserId);
    }
    
    await this.refreshConversations();
  }

  async sendMessage(): Promise<void> {
    if (!this.newMessage.trim() || !this.selectedConversation) return;

    const content = this.newMessage.trim();
    this.newMessage = '';

    // Stop typing indicator
    if (this.selectedConversation) {
      this.chatService.sendTypingNotification(this.selectedConversation.otherUserId, false);
    }

    // Clear typing timeouts
    if (this.typingTimeout) {
      clearTimeout(this.typingTimeout);
      this.typingTimeout = null;
    }
    if (this.stopTypingTimeout) {
      clearTimeout(this.stopTypingTimeout);
      this.stopTypingTimeout = null;
    }

    this.chatService.sendMessage(this.selectedConversation!.otherUserId, content);
    
    // Optimistically add message to UI - will be replaced by server response
    if (this.currentUserId) {
      const optimisticMessage: Message = {
        senderId: this.currentUserId,
        senderName: 'You',
        receiverId: this.selectedConversation!.otherUserId,
        receiverName: this.selectedConversation!.otherUserName,
        content,
        isRead: false,
        createdAt: new Date().toISOString()
      };
      this.messages.push(optimisticMessage);
      this.shouldScrollToBottom = true;
    }
  }

  onMessageInput(): void {
    if (!this.selectedConversation) return;

    // Clear any existing stop typing timeout
    if (this.stopTypingTimeout) {
      clearTimeout(this.stopTypingTimeout);
      this.stopTypingTimeout = null;
    }

    const now = Date.now();
    // Debounce typing notifications - send max once per second
    if (now - this.lastTypingNotification > 1000) {
      this.chatService.sendTypingNotification(this.selectedConversation.otherUserId, true);
      this.lastTypingNotification = now;
    }

    // If user stops typing for 2 seconds, send stop typing notification
    this.stopTypingTimeout = setTimeout(() => {
      if (this.selectedConversation) {
        this.chatService.sendTypingNotification(this.selectedConversation.otherUserId, false);
      }
    }, 2000);
  }

  onMessageKeyDown(event: KeyboardEvent): void {
    if (!this.selectedConversation) return;

    // When Enter is pressed without Shift, send message and prevent new line
    if (event.key === 'Enter' && !event.shiftKey) {
      event.preventDefault(); // Prevent default behavior (new line)
      // Stop typing indicator
      this.chatService.sendTypingNotification(this.selectedConversation.otherUserId, false);
      // Send message if there's content
      if (this.newMessage.trim()) {
        this.sendMessage();
      }
    }
    // Shift+Enter will allow default behavior (new line)
  }

  async refreshConversations(): Promise<void> {
    await this.chatService.refreshConversations();
  }

  getLastSeenTime(lastSeen?: string): string {
    if (!lastSeen) return 'recently';
    
    const lastSeenDate = new Date(lastSeen);
    const now = new Date();
    const diffMs = now.getTime() - lastSeenDate.getTime();
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMs / 3600000);
    const diffDays = Math.floor(diffMs / 86400000);

    if (diffMins < 1) return 'just now';
    if (diffMins < 60) return `${diffMins} minute${diffMins !== 1 ? 's' : ''} ago`;
    if (diffHours < 24) return `${diffHours} hour${diffHours !== 1 ? 's' : ''} ago`;
    if (diffDays < 7) return `${diffDays} day${diffDays !== 1 ? 's' : ''} ago`;
    
    return lastSeenDate.toLocaleDateString();
  }

  getMessageTime(timestamp: string): string {
    const date = new Date(timestamp);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / 60000);
    
    if (diffMins < 1) return 'Just now';
    if (diffMins < 60) return `${diffMins}m ago`;
    if (diffMins < 1440) return `${Math.floor(diffMins / 60)}h ago`;
    
    return date.toLocaleDateString();
  }

  isMyMessage(message: Message): boolean {
    if (!this.currentUserId) return false;
    return message.senderId === this.currentUserId;
  }

  private scrollToBottom(): void {
    try {
      if (this.messagesContainer) {
        this.messagesContainer.nativeElement.scrollTop = 
          this.messagesContainer.nativeElement.scrollHeight;
      }
    } catch (err) {
      this.logger.error('Error scrolling to bottom:', err);
    }
  }

  getConversationPreview(conversation: Conversation): string {
    if (!conversation.lastMessage) return 'No messages yet';
    const preview = conversation.lastMessage.content.substring(0, 50);
    return preview.length < conversation.lastMessage.content.length ? preview + '...' : preview;
  }

  toggleSearch(): void {
    this.showSearch = !this.showSearch;
    if (this.showSearch) {
      this.searchQuery = '';
      this.searchResults = [];
      this.loadAllUsers();
    }
  }

  onSearchInput(): void {
    this.searchSubject.next(this.searchQuery);
  }

  private async performSearch(query: string): Promise<void> {
    if (!query.trim()) {
      await this.loadAllUsers();
      return;
    }

    this.isSearching = true;
    try {
      if (this.currentUser?.role === 'PATIENT') {
        this.searchResults = await this.chatService.searchDoctors(query);
      } else if (this.currentUser?.role === 'DOCTOR') {
        this.searchResults = await this.chatService.searchPatients(query);
      }
    } catch (error) {
      this.logger.error('Search error:', error);
      this.searchResults = [];
    } finally {
      this.isSearching = false;
    }
  }

  private async loadAllUsers(): Promise<void> {
    this.isSearching = true;
    try {
      if (this.currentUser?.role === 'PATIENT') {
        this.searchResults = await this.chatService.searchDoctors('');
      } else if (this.currentUser?.role === 'DOCTOR') {
        this.searchResults = await this.chatService.searchPatients('');
      }
    } catch (error) {
      this.logger.error('Error loading users:', error);
      this.searchResults = [];
    } finally {
      this.isSearching = false;
    }
  }

  async startConversation(user: ChatUser): Promise<void> {
    // Check if conversation already exists
    const existing = this.conversations.find(c => c.otherUserId === user.userId);
    if (existing) {
      this.selectConversation(existing);
      this.showSearch = false;
      this.searchQuery = '';
      return;
    }

    // Create new conversation
    const conversation = await this.chatService.startConversationWithUser(user.userId);
    if (conversation) {
      // Add to conversations list
      this.conversations.unshift(conversation);
      this.selectConversation(conversation);
      this.showSearch = false;
      this.searchQuery = '';
      // Load messages for this conversation
      this.messages = await this.chatService.getConversation(user.userId);
      this.shouldScrollToBottom = true;
    }
  }

  getUserFullName(user: ChatUser): string {
    return `${user.firstName} ${user.lastName}`;
  }

  trackByUserId(index: number, user: ChatUser): string {
    return user.userId;
  }

  trackByMessageId(index: number, message: Message): string {
    return message.id || `${message.senderId}-${message.createdAt}-${index}`;
  }


  // Public method to open a conversation by userId (called from parent components)
  async openConversation(userId: string): Promise<void> {
    this.logger.debug('ChatComponent: Opening conversation for user:', userId);
    
    // Check if conversation already exists
    const existingConversation = this.conversations.find(c => c.otherUserId === userId);
    if (existingConversation) {
      await this.selectConversation(existingConversation);
      return;
    }
    
    // If conversation doesn't exist, try to start a new one
    try {
      const conversation = await this.chatService.startConversationWithUser(userId);
      if (conversation) {
        // Add to conversations if not already there
        if (!this.conversations.find(c => c.otherUserId === userId)) {
          this.conversations.unshift(conversation);
        }
        await this.selectConversation(conversation);
      }
    } catch (error) {
      this.logger.error('Error opening conversation:', error);
    }
  }

  onImageError(event: Event): void {
    const img = event.target as HTMLImageElement;
    if (img) {
      // Hide the failed image
      img.style.display = 'none';
      // Show the avatar fallback (first letter) when image fails to load
      const avatarContainer = img.parentElement;
      if (avatarContainer) {
        const fallback = avatarContainer.querySelector('.avatar-fallback') as HTMLElement;
        if (fallback) {
          fallback.style.display = 'flex';
          // Remove the data-visible attribute to allow manual control
          fallback.removeAttribute('data-visible');
        }
      }
    }
  }

  async deleteMessage(message: Message): Promise<void> {
    if (!message.id) {
      this.logger.warn('Cannot delete message without ID');
      return;
    }

    this.messageToDelete = message;
    this.deleteModalType = 'message';
    this.showDeleteModal = true;
  }

  async deleteConversation(): Promise<void> {
    if (!this.selectedConversation) return;

    this.deleteModalType = 'conversation';
    this.showDeleteModal = true;
  }

  async confirmDelete(): Promise<void> {
    if (this.deleteModalType === 'message' && this.messageToDelete?.id) {
      try {
        await this.chatService.deleteMessage(this.messageToDelete.id);
        // Remove message from local list
        this.messages = this.messages.filter(m => m.id !== this.messageToDelete?.id);
        // Refresh conversations to update unread counts
        await this.refreshConversations();
        this.closeDeleteModal();
      } catch (error: any) {
        this.logger.error('Error deleting message:', error);
        await this.modalService.alert(
          error?.response?.data?.message || 'Failed to delete message. Please try again.',
          'error',
          'Delete Error'
        );
        this.closeDeleteModal();
      }
    } else if (this.deleteModalType === 'conversation' && this.selectedConversation) {
      try {
        // Delete conversation for current user only (backend handles this)
        await this.chatService.deleteConversation(this.selectedConversation.otherUserId);
        // Clear messages from current user's view
        this.messages = [];
        // Deselect conversation
        this.selectedConversation = null;
        // Clear active conversation in notification service
        this.notificationService.clearActiveConversation();
        // Refresh conversations list (conversation will be removed for current user only)
        await this.refreshConversations();
        this.closeDeleteModal();
      } catch (error: any) {
        this.logger.error('Error deleting conversation:', error);
        await this.modalService.alert(
          error?.response?.data?.message || 'Failed to delete conversation. Please try again.',
          'error',
          'Delete Error'
        );
        this.closeDeleteModal();
      }
    }
  }

  closeDeleteModal(): void {
    this.showDeleteModal = false;
    this.messageToDelete = null;
    this.deleteModalType = 'conversation';
  }

  getDeleteModalTitle(): string {
    if (this.deleteModalType === 'message') {
      return 'Delete Message';
    }
    return 'Delete All Messages';
  }

  getDeleteModalMessage(): string {
    if (this.deleteModalType === 'message') {
      return 'Are you sure you want to delete this message? This action cannot be undone.';
    }
    if (this.selectedConversation) {
      return `Are you sure you want to delete this conversation? This will remove all messages from your chat history. The other person will still be able to see their messages. This action cannot be undone.`;
    }
    return 'Are you sure you want to delete all messages?';
  }

  async startVideoCall(): Promise<void> {
    if (!this.selectedConversation) {
      await this.modalService.alert(
        'Please select a conversation first',
        'warning',
        'No Conversation Selected'
      );
      return;
    }

    // Check if the other user is offline
    if (!this.selectedConversation.isOnline || this.selectedConversation.otherUserStatus === 'OFFLINE') {
      await this.modalService.alert(
        `${this.selectedConversation.otherUserName} is currently offline and cannot receive calls. Please try again later.`,
        'warning',
        'User Offline'
      );
      return;
    }

    try {
      this.logger.debug('Starting video call to:', this.selectedConversation.otherUserId);
      await this.callService.initiateCall(this.selectedConversation.otherUserId, 'video');
    } catch (error: any) {
      this.logger.error('Error starting video call:', error);
      await this.modalService.alert(
        error?.message || 'Failed to start video call. Please ensure you are connected and try again.',
        'error',
        'Call Error'
      );
    }
  }

  async startAudioCall(): Promise<void> {
    if (!this.selectedConversation) {
      await this.modalService.alert(
        'Please select a conversation first',
        'warning',
        'No Conversation Selected'
      );
      return;
    }

    // Check if the other user is offline
    if (!this.selectedConversation.isOnline || this.selectedConversation.otherUserStatus === 'OFFLINE') {
      await this.modalService.alert(
        `${this.selectedConversation.otherUserName} is currently offline and cannot receive calls. Please try again later.`,
        'warning',
        'User Offline'
      );
      return;
    }

    try {
      this.logger.debug('Starting audio call to:', this.selectedConversation.otherUserId);
      await this.callService.initiateCall(this.selectedConversation.otherUserId, 'audio');
    } catch (error: any) {
      this.logger.error('Error starting audio call:', error);
      await this.modalService.alert(
        error?.message || 'Failed to start audio call. Please ensure you are connected and try again.',
        'error',
        'Call Error'
      );
    }
  }

  async setUserStatus(status: 'ONLINE' | 'OFFLINE' | 'BUSY'): Promise<void> {
    try {
      await this.chatService.updateUserStatus(status);
      // Update local state immediately for responsive UI
      this.currentUserStatus = status;
      // Clear user cache to force reload of user profile with new status
      this.userService.clearUserCache();
      // Update current user object if available
      if (this.currentUser) {
        this.currentUser.status = status;
        this.currentUser.isOnline = (status === 'ONLINE' || status === 'BUSY');
      }
      this.showStatusMenu = false;
      this.logger.debug('User status updated to:', status);
    } catch (error: any) {
      this.logger.error('Error updating user status:', error);
      await this.modalService.alert(
        error?.message || 'Failed to update status. Please try again.',
        'error',
        'Update Error'
      );
    }
  }

  getStatusLabel(status?: 'ONLINE' | 'OFFLINE' | 'BUSY'): string {
    if (!status) {
      return 'Offline';
    }
    switch (status) {
      case 'ONLINE':
        return 'Online';
      case 'BUSY':
        return 'Busy';
      case 'OFFLINE':
      default:
        return 'Offline';
    }
  }

  toggleBlockedUsers(): void {
    this.showBlockedUsers = !this.showBlockedUsers;
    if (this.showBlockedUsers) {
      this.loadBlockedUsers();
    }
    // Close search if open
    if (this.showSearch) {
      this.showSearch = false;
    }
  }

  async loadBlockedUsers(): Promise<void> {
    this.isLoadingBlockedUsers = true;
    try {
      this.blockedUsers = await this.chatService.getBlockedUsersWithDetails();
    } catch (error) {
      this.logger.error('Error loading blocked users:', error);
      this.blockedUsers = [];
    } finally {
      this.isLoadingBlockedUsers = false;
    }
  }

  async blockUser(): Promise<void> {
    if (!this.selectedConversation) return;
    
    try {
      const confirmed = await this.modalService.confirm(
        `Are you sure you want to block ${this.selectedConversation.otherUserName}? You won't be able to send or receive messages from them.`,
        'Block User',
        'Block',
        'Cancel'
      );
      
      if (!confirmed) return;
      
      await this.chatService.blockUser(this.selectedConversation.otherUserId);
      this.isUserBlocked = true;
      
      // Refresh conversations and blocked users list
      await this.refreshConversations();
      if (this.showBlockedUsers) {
        await this.loadBlockedUsers();
      }
      
      // Show success message
      await this.modalService.alert(
        `${this.selectedConversation.otherUserName} has been blocked successfully.`,
        'success',
        'User Blocked'
      );
    } catch (error: any) {
      this.logger.error('Error blocking user:', error);
      let errorMessage = 'Failed to block user. Please try again.';
      if (error?.response?.data?.message) {
        errorMessage = error.response.data.message;
      } else if (error?.response?.data?.error) {
        errorMessage = error.response.data.error;
      } else if (error?.message) {
        errorMessage = error.message;
      }
      
      await this.modalService.alert(errorMessage, 'error', 'Error');
    }
  }

  async unblockUser(user: ChatUser): Promise<void> {
    try {
      this.logger.debug('Unblocking user:', user.userId, user);
      // Ensure userId is a string and trim any whitespace
      const userId = String(user.userId).trim();
      if (!userId) {
        throw new Error('Invalid user ID');
      }
      await this.chatService.unblockUser(userId);
      
      // Update isUserBlocked if this is the currently selected user
      if (this.selectedConversation && this.selectedConversation.otherUserId === userId) {
        this.isUserBlocked = false;
      }
      
      // Remove from blocked users list
      this.blockedUsers = this.blockedUsers.filter(u => u.userId !== user.userId);
      // Refresh conversations to show unblocked user
      await this.refreshConversations();
      // Show success message
      const userName = user.firstName && user.lastName 
        ? `${user.firstName} ${user.lastName}` 
        : user.userId || 'User';
      await this.modalService.alert(
        `${userName} has been unblocked successfully.`,
        'success',
        'User Unblocked'
      );
    } catch (error: any) {
      this.logger.error('Error unblocking user:', error, {
        message: error?.message,
        response: error?.response?.data,
        status: error?.response?.status
      });
      let errorMessage = 'Failed to unblock user. Please try again.';
      if (error?.response?.data?.message) {
        errorMessage = error.response.data.message;
      } else if (error?.message) {
        errorMessage = error.message;
      }
      await this.modalService.alert(
        errorMessage,
        'error',
        'Unblock Error'
      );
    }
  }

  async unblockSelectedUser(): Promise<void> {
    if (!this.selectedConversation) return;
    
    const user: ChatUser = {
      userId: this.selectedConversation.otherUserId,
      firstName: this.selectedConversation.otherUserName.split(' ')[0] || '',
      lastName: this.selectedConversation.otherUserName.split(' ').slice(1).join(' ') || '',
      avatarUrl: this.selectedConversation.otherUserAvatarUrl || '',
      isOnline: this.selectedConversation.isOnline || false,
      status: this.selectedConversation.otherUserStatus
    };
    
    await this.unblockUser(user);
  }
}

