import {Component, CUSTOM_ELEMENTS_SCHEMA, inject, OnInit} from '@angular/core';
//import {NavigationComponent} from '../navigation/navigation.component';

import {Router, RouterLink, RouterOutlet} from '@angular/router';
import {MatToolbar} from '@angular/material/toolbar';
import {MatButton, MatFabButton, MatMiniFabButton} from '@angular/material/button';
import {IconDirective, IconService} from '@ant-design/icons-angular';
import {MatDialog} from '@angular/material/dialog';
import {Subscription} from 'rxjs';
import {TokenStorageService} from '../../services/token-storage.service';
import {AuthService} from '../../services/auth.service';
import {EventBusService} from '../../_shared/event-bus.service';
import {DialogComponent} from '../../components/dialog/dialog.component';

import {CommonModule} from '@angular/common';
import {MatIcon} from '@angular/material/icon';
import {MatMenu, MatMenuItem, MatMenuTrigger} from '@angular/material/menu';
import {MatTooltip} from '@angular/material/tooltip';
import {DialogSignupComponent} from '../../components/dialog-signup.component/dialog-signup.component';
import {MatLabel} from '@angular/material/input';

@Component({
  selector: 'app-main.component',
  imports: [

    MatToolbar,
    MatButton,
    RouterLink,
    IconDirective,
    RouterOutlet,
    CommonModule,
    MatIcon,
    MatMiniFabButton,
    MatMenuTrigger,
    MatMenu,
    MatMenuItem,
    MatTooltip,
    MatLabel,
    MatFabButton

  ],
  schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
  templateUrl: './main.component.html',
  styleUrl: './main.component.scss'
})
export class MainComponent implements OnInit{
  // public props
  navCollapsed: boolean = false;
  navCollapsedMob: boolean = false;

  readonly dialog = inject(MatDialog);
  //private  authService = new AuthService(provideHttpClient())
  public dialogLoginData : DialogLoginData = {password: "", username: ""};
  public dialogSignupData : DialogSignupData = {password: "", username: "", email: "", confirmPassword: ""};


  private roles: string[] = [];
  isLoggedIn = false;
  showAdminBoard = false;
  showModeratorBoard = false;
  username?: string;

  eventBusSub?: Subscription;


  private storageService: TokenStorageService = inject(TokenStorageService);
  private authService: AuthService = inject(AuthService);
  private eventBusService: EventBusService = inject(EventBusService);

  constructor(private router: Router) {

  }
  goToHome() {
    this.router.navigate(['main/home']);
  }

  ngOnInit(): void {
    this.isLoggedIn = this.storageService.isLoggedIn();

    this.refreshToolbar();

    this.eventBusSub = this.eventBusService.on('logout', () => {
      this.logout();
    });
  }

  refreshToolbar() {
    if (this.isLoggedIn) {
      const user = this.storageService.getUser();
      this.roles = user.roles;

      this.showAdminBoard = true;//this.roles.includes('ROLE_ADMIN');
      this.showModeratorBoard = this.roles.includes('ROLE_MODERATOR');

      this.username = user.username;
    }
  }

  ngOnDestroy() {
    if (this.eventBusSub) {
      this.eventBusSub.unsubscribe();
    }
  }

  // public method
  navMobClick() {
    if (this.navCollapsedMob && !document.querySelector('app-navigation.pc-sidebar')?.classList.contains('mob-open')) {
      this.navCollapsedMob = !this.navCollapsedMob;
      setTimeout(() => {
        this.navCollapsedMob = !this.navCollapsedMob;
      }, 100);
    } else {
      this.navCollapsedMob = !this.navCollapsedMob;
    }
    if (document.querySelector('app-navigation.pc-sidebar')?.classList.contains('navbar-collapsed')) {
      document.querySelector('app-navigation.pc-sidebar')?.classList.remove('navbar-collapsed');
    }
  }

  handleKeyDown(event: KeyboardEvent): void {
    if (event.key === 'Escape') {
      this.closeMenu();
    }
  }

  closeMenu() {
    if (document.querySelector('app-navigation.pc-sidebar')?.classList.contains('mob-open')) {
      document.querySelector('app-navigation.pc-sidebar')?.classList.remove('mob-open');
    }
  }


  logout(): void {
    this.authService.logout().subscribe({
      next: res => {
        console.log(res);
        this.storageService.clean();

        window.location.reload();
      },
      error: err => {
        console.log(err);
      }
    });
  }

  openLoginDialog(enterAnimationDuration: string, exitAnimationDuration: string) {

    let dialogLoginRef = this.dialog.open(DialogComponent, {
      width: '350px',
      enterAnimationDuration,
      exitAnimationDuration,
      data: {username: this.dialogLoginData.username, password: this.dialogLoginData.password}
    });
    dialogLoginRef.componentInstance.signupClicked.subscribe(result => {
      dialogLoginRef.close();
      this.openSignupDialog(enterAnimationDuration, exitAnimationDuration);
    })

    const dialogSubmitSubscription = dialogLoginRef.componentInstance.loginClicked
      .subscribe(result => {
        console.log('Got the data!', result);

        if(result== null){
          return;
        }
        this.dialogLoginData = result;

        this.authService.login(this.dialogLoginData.username, this.dialogLoginData.password).subscribe(
          data => {
            this.storageService.saveToken(data.accessToken);
            this.storageService.saveUser(data);

            this.isLoggedIn = true;
            let user = this.storageService.getUser();
            this.roles = user.roles;

            this.refreshToolbar();
            dialogLoginRef.close()
            this.router.navigate(['main/user/user-welcome']);
          },
          err => {
            dialogLoginRef.componentInstance.openLoginFailedSnackBar(err.error.message);
          }
        );

        // do something here with the data
        dialogSubmitSubscription.unsubscribe();
      });
  }

  openSignupDialog(enterAnimationDuration: string, exitAnimationDuration: string) {

    let dialogSignupRef = this.dialog.open(DialogSignupComponent, {
      width: '350px',
      enterAnimationDuration,
      exitAnimationDuration,
      data: {username: this.dialogLoginData.username, password: this.dialogLoginData.password}
    });

    const dialogloginSubscription = dialogSignupRef.componentInstance.loginClicked.subscribe(result => {
      dialogSignupRef.close();
      this.openLoginDialog(enterAnimationDuration, exitAnimationDuration);
    })

    const dialogSubmitSubscription = dialogSignupRef.componentInstance.signupClicked
      .subscribe(result => {
        console.log('Got the data!', result);

        if (result == null) {
          return;
        }
        this.dialogSignupData = result;

        this.authService.register(this.dialogSignupData.username, this.dialogSignupData.email, this.dialogSignupData.password).subscribe(
          data => {
            console.log(data);
            dialogSignupRef.componentInstance.openSignupSuccessSnackBar(data.message)
            dialogSignupRef.close();
          },
          err => {
            dialogSignupRef.componentInstance.openSignupFailedSnackBar(err.error.message);
          }
        );

        // do something here with the data
        dialogloginSubscription.unsubscribe();
        dialogSubmitSubscription.unsubscribe();
      });
  }
}
export interface DialogLoginData {
  username: string;
  password: string;
}

export interface DialogSignupData {
  email: string;
  username: string;
  password: string;
  confirmPassword: string;
}
