import { Component, computed, inject, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
  ActivatedRoute,
  Router,
  RouterLink,
  RouterLinkActive,
  RouterOutlet,
} from '@angular/router';
import { MatBadgeModule } from '@angular/material/badge';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { MatToolbarModule } from '@angular/material/toolbar';
import { AuthStore } from '../../auth/auth-store';
import { MyTeamsStore } from '../../team/my-teams-store';
import { TeamStore } from '../../team/team-store';
import { NotificationsStore } from '../../notifications/notifications-store';
import {
  notificationIcon,
  notificationLabel,
  notificationTarget,
} from '../../notifications/notification-presentation';
import { UserTeamReference } from '../../../models/user-directory.model';
import { NotificationItem } from '../../../models/notification.model';

@Component({
  selector: 'app-shell',
  imports: [
    RouterOutlet,
    RouterLink,
    RouterLinkActive,
    MatToolbarModule,
    MatIconModule,
    MatMenuModule,
    MatButtonModule,
    MatBadgeModule,
  ],
  templateUrl: './shell.html',
  styleUrl: './shell.scss',
})
export class Shell {
  private readonly route = inject(ActivatedRoute);
  private readonly router = inject(Router);
  private readonly authStore = inject(AuthStore);
  private readonly myTeamsStore = inject(MyTeamsStore);
  private readonly teamStore = inject(TeamStore);
  private readonly notificationsStore = inject(NotificationsStore);

  protected readonly currentTeam = this.teamStore.team;
  protected readonly currentTeamId = signal<number | null>(null);
  protected readonly unreadCount = this.notificationsStore.unreadCount;
  protected readonly notifications = this.notificationsStore.notifications;

  protected readonly myTeams = computed(() => {
    const seen = new Set<number>();
    const teams: UserTeamReference[] = [];
    for (const player of this.myTeamsStore.players()) {
      if (!seen.has(player.team.id)) {
        seen.add(player.team.id);
        teams.push(player.team);
      }
    }
    return teams;
  });

  constructor() {
    const userId = this.authStore.currentUser()?.id;
    if (userId) {
      this.myTeamsStore.ensureLoaded(userId);
    }

    this.route.paramMap.pipe(takeUntilDestroyed()).subscribe((params) => {
      const raw = params.get('id');
      const id = raw === null ? Number.NaN : Number(raw);
      if (Number.isInteger(id) && id > 0) {
        this.teamStore.loadTeam(id);
        this.currentTeamId.set(id);
        this.notificationsStore.startPolling(id);
      }
    });
  }

  protected switchTeam(teamId: number): void {
    void this.router.navigate(['/team', teamId, 'overview']);
  }

  protected notificationLabel(item: NotificationItem): string {
    return notificationLabel(item);
  }

  protected notificationIcon(item: NotificationItem): string {
    return notificationIcon(item.event);
  }

  protected onNotificationsMenuOpened(): void {
    const teamId = this.currentTeamId();
    if (teamId !== null) {
      this.notificationsStore.loadRecent(teamId);
    }
  }

  protected onNotificationClick(item: NotificationItem): void {
    const teamId = this.currentTeamId();
    if (teamId === null) return;
    this.notificationsStore.markRead(teamId, item.id);
    void this.router.navigate(notificationTarget(item, teamId));
  }

  protected onMarkAllRead(): void {
    const teamId = this.currentTeamId();
    if (teamId !== null) {
      this.notificationsStore.markAllRead(teamId);
    }
  }
}
