import { Component, EventEmitter, Input, Output, ChangeDetectionStrategy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Notification } from '../../../../services/notification.service';
import { UserInfo, UserService } from '../../../../services/user.service';
import { ChatUser, Conversation } from '../../../../services/chat.service';

@Component({
  selector: 'app-patient-dashboard-header',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './patient-dashboard-header.component.html',
  styleUrls: ['./patient-dashboard-header.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class PatientDashboardHeaderComponent {
  @Input() currentUser: UserInfo | null = null;
  @Input() notificationCount = 0;
  @Input() notifications: Notification[] = [];
  @Input() showNotifications = false;
  @Input() loading = false;
  @Input() chatUnreadCount = 0;
  @Input() showChatMenu = false;
  @Input() showBlockedUsers = false;
  @Input() blockedUsers: ChatUser[] = [];
  @Input() isLoadingBlockedUsers = false;
  @Input() chatSearchQuery = '';
  @Input() chatSearchResults: ChatUser[] = [];
  @Input() filteredConversations: Conversation[] = [];
  @Input() conversations: Conversation[] = [];
  @Input() activeConversationId: string | null = null;

  @Output() refresh = new EventEmitter<void>();
  @Output() logout = new EventEmitter<void>();
  @Output() toggleNotifications = new EventEmitter<void>();
  @Output() markAllNotificationsAsRead = new EventEmitter<void>();
  @Output() deleteAllNotifications = new EventEmitter<void>();
  @Output() deleteNotification = new EventEmitter<string>();
  @Output() notificationClick = new EventEmitter<Notification>();
  @Output() toggleChatMenu = new EventEmitter<void>();
  @Output() toggleBlockedUsers = new EventEmitter<void>();
  @Output() chatSearch = new EventEmitter<string>();
  @Output() clearChatSearch = new EventEmitter<void>();
  @Output() openChatConversation = new EventEmitter<string>();
  @Output() openChatWithUser = new EventEmitter<string>();
  @Output() unblockUser = new EventEmitter<ChatUser>();

  constructor(public userService: UserService) {}

  onToggleNotifications(): void {
    this.toggleNotifications.emit();
  }

  onRefresh(): void {
    this.refresh.emit();
  }

  onLogout(): void {
    this.logout.emit();
  }

  onMarkAllRead(event: MouseEvent): void {
    event.stopPropagation();
    this.markAllNotificationsAsRead.emit();
  }

  onDeleteAll(event: MouseEvent): void {
    event.stopPropagation();
    this.deleteAllNotifications.emit();
  }

  onDeleteNotification(notificationId: string, event: MouseEvent): void {
    event.stopPropagation();
    this.deleteNotification.emit(notificationId);
  }

  onNotificationClick(notification: Notification): void {
    this.notificationClick.emit(notification);
  }

  onToggleChatMenu(): void {
    this.toggleChatMenu.emit();
  }

  onToggleBlockedUsers(event?: MouseEvent): void {
    event?.stopPropagation();
    this.toggleBlockedUsers.emit();
  }

  onChatSearch(event: Event): void {
    const input = event.target as HTMLInputElement;
    this.chatSearch.emit(input.value);
  }

  onClearChatSearch(event?: MouseEvent): void {
    event?.stopPropagation();
    this.clearChatSearch.emit();
  }

  onOpenChatConversation(userId: string): void {
    this.openChatConversation.emit(userId);
  }

  onOpenChatWithUser(userId: string): void {
    this.openChatWithUser.emit(userId);
  }

  onUnblockUser(user: ChatUser, event: Event): void {
    event.stopPropagation();
    event.preventDefault();
    this.unblockUser.emit(user);
  }

  getNotificationTime(timestamp: Date): string {
    const now = new Date();
    const diffMs = now.getTime() - new Date(timestamp).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 new Date(timestamp).toLocaleDateString();
  }

  getConversationTime(timestamp?: string | Date): string {
    if (!timestamp) return '';
    const date = new Date(timestamp);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMs / 3600000);
    const diffDays = Math.floor(diffMs / 86400000);

    if (diffMins < 1) return 'Now';
    if (diffMins < 60) return `${diffMins}m`;
    if (diffHours < 24) return `${diffHours}h`;
    if (diffDays < 7) return `${diffDays}d`;

    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
  }

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

  onChatImageError(event: Event): void {
    const img = event.target as HTMLImageElement;
    img.style.display = 'none';
    const avatarCircle = img.nextElementSibling as HTMLElement;
    if (avatarCircle) {
      avatarCircle.style.display = 'flex';
    }
  }
}

