import {Component, computed, HostListener, inject, input, OnDestroy, Signal} from '@angular/core';
import {CommonModule, NgOptimizedImage} from '@angular/common';
import {ThemeComponent} from '@shared-components/theme/theme.component';
import {RouterLink} from '@angular/router';
import {AuthService} from '@services/auth.service';
import {Subscription} from 'rxjs';
import {LoginDialogComponent} from '@shared-components/login/login.component';
import {MatDialog} from '@angular/material/dialog';
import {PermissionClaim} from '@api';

@Component({
  standalone: true,
  imports: [
    CommonModule,
    ThemeComponent,
    RouterLink,
    NgOptimizedImage
  ],
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnDestroy {

  private authService: AuthService = inject(AuthService)
  private dialog: MatDialog = inject(MatDialog)

  current_page = input.required<string>();
  background_image = input.required<string>();
  height = input.required<string>();
  overlay_gradient = input.required<number>();

  public active: string = '';
  public inverseYPos: number = 0;
  private subscription: Subscription | undefined;
  public isAuthenticated: Signal<boolean> = computed(() => this.authService.isAuthenticated$());

  ngOnDestroy(): void {
    this.subscription?.unsubscribe();
  }

  @HostListener('window:scroll', [])
  onWindowScroll(): void {
    const scrollPosition = window.scrollY;
    if (scrollPosition > 5) {
      this.active = 'active';
      this.inverseYPos = scrollPosition - (scrollPosition * 0.2);
    } else {
      this.inverseYPos = 0;
      this.active = '';
    }
  }

  public getBackgroundImage() {
    if (this.overlay_gradient()) {
      return `linear-gradient(rgba(0, 0, 0, ${this.overlay_gradient()}), rgba(0, 0, 0, ${this.overlay_gradient()})), url(${this.background_image()})`;
    } else {
      return `url(${this.background_image()})`;
    }
  }


  public getCurrentPageId(options: string[]) {
    if (options.includes(this.current_page())) {
      return 'current_page'
    }
    return null;
  }

  public getBackgroundPosition() {
    if (this.current_page() === 'home') {
      return 'center ' + this.inverseYPos + 'px'
    } else {
      return '';
    }
  }

  public openLoginDialog() {
    const dialogRef = this.dialog.open(LoginDialogComponent, {
      width: '400px',
    })
    dialogRef.afterClosed().subscribe(result => {
      console.log(result);
    });
  }

  public hasAccess(claims: string[]): boolean {
    return this.authService.hasAccess(claims)
  }

  protected logout() {
    this.authService.logout()
  }

  protected readonly PermissionClaim = PermissionClaim;
}
