import { Component, computed, inject } from '@angular/core';
import { Router, RouterLink } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatDialog } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { AuthStore } from '../../../core/auth/auth-store';
import { HelpAccessService } from '../../../core/help/help-access';
import { MyTeamsStore } from '../../../core/team/my-teams-store';
import { TeamPermissionsService } from '../../../core/team/team-permissions';
import { TeamStore } from '../../../core/team/team-store';
import { Team } from '../../../models/team.model';
import { CreateTeamDialog } from '../../team-select/create-team-dialog/create-team-dialog';

@Component({
  selector: 'app-more',
  imports: [RouterLink, MatButtonModule, MatCardModule, MatIconModule],
  templateUrl: './more.html',
  styleUrl: './more.scss',
})
export class More {
  private readonly authStore = inject(AuthStore);
  private readonly dialog = inject(MatDialog);
  private readonly helpAccess = inject(HelpAccessService);
  private readonly myTeamsStore = inject(MyTeamsStore);
  private readonly permissions = inject(TeamPermissionsService);
  private readonly router = inject(Router);
  private readonly teamStore = inject(TeamStore);
  protected readonly user = this.authStore.currentUser;
  protected readonly canOpenGuide = this.helpAccess.canOpenGuide;
  protected readonly canManagePermissions = computed(() =>
    this.permissions.canDo(this.teamStore.team(), 'memberManage'),
  );

  protected logout(): void {
    this.authStore.clearSession();
    void this.router.navigateByUrl('/auth/login');
  }

  protected createTeam(): void {
    this.dialog
      .open(CreateTeamDialog)
      .afterClosed()
      .subscribe((team: Team | undefined) => {
        if (!team) return;

        const userId = this.authStore.currentUser()?.id;
        if (userId) {
          this.myTeamsStore.refresh(userId);
        }
        void this.router.navigate(['/team', team.id, 'overview']);
      });
  }
}
