import { AfterViewInit, Component, NgZone, OnInit, ViewChild } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { DialogService } from '@progress/kendo-angular-dialog';
import { TextBoxComponent } from '@progress/kendo-angular-inputs';
import { thumbnailsUpIcon } from '@progress/kendo-svg-icons';
import { ResultApi } from 'src/app/models/result-api.model';
import { MessageFailureComponent } from 'src/app/shared/menssages/message-failure/message-failure.component';
import { AuthService } from '../services/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss',
    './login.component.css']
})
export class LoginComponent implements OnInit, AfterViewInit {
  @ViewChild('password') public textbox: TextBoxComponent;
  public initialPassword = true;
  public passwordVisible = false;
  public loadingIcon = '';

  public form: FormGroup;
  public data: any = {
    email: '',
    password: '',
  };

  constructor(private authService: AuthService,
    private router: Router,
    private dialogService: DialogService,
    private ngZone: NgZone
  ) {
    this.form = new FormGroup({
      password: new FormControl(this.data.password, [Validators.required, Validators.minLength(3)]),
      email: new FormControl(this.data.email, [
        Validators.required,
      ]),
    });
  }

  private dialog: any;

  public onEnter(event: KeyboardEvent): void {
    event.preventDefault(); // Evita o envio do formulário padrão
    if (this.form.valid) {
      this.submitForm(); // Apenas submete se o formulário for válido
    }
  }


  public submitForm(): void {
    this.form.markAllAsTouched();
    if (this.form.valid) {
      this.loadingIcon = 'loading';
      //   const domain = '@jurunense.com.br';
      let email = this.form.value.email;

      // Remover domínio existente se já foi digitado
      // if (email.toLowerCase().endsWith(domain)) {
      //     email = email.substring(0, email.length - domain.length);
      //  }

      const emailUpperCase = (email).toUpperCase();
      const passwordUpperCase = this.form.value.password.toUpperCase();

      this.authService.login({
        email: emailUpperCase,
        password: passwordUpperCase
      })
        .subscribe((res: ResultApi) => {
          if (res.success) {
            this.loadingIcon = '';
            console.log(JSON.stringify(res.data));
            this.authService.setDataInLocalStorage('user', JSON.stringify(res.data));
            this.authService.setDataInLocalStorage('token', res.data.token);
            localStorage.removeItem('cart');
            this.router.navigate(['/sales/menu']);
          } else {
            this.loadingIcon = '';
            this.showErrorMessage(res.message);
          }
        }, err => {
          this.loadingIcon = '';
          this.showErrorMessage(`${err.error.message}`);
        });
    }
  }

  public get isLoading(): boolean {
    return this.loadingIcon !== '';
  }

  public clearForm(): void {
    this.form.reset();
  }

  public togglePass(): void {
    const inputEl = this.textbox.input.nativeElement;

    if (this.initialPassword) {
      inputEl.type = 'password';
      this.initialPassword = false;
      return;
    }

    if (inputEl.type === 'password') {
      inputEl.type = 'text';
    } else {
      inputEl.type = 'password';
    }

    console.log(this.form.controls.password.value);
  }

  getUserName() {
    return this.authService.getUserName();
  }

  showErrorMessage(message: string) {
    console.log('mensagem de erro', message);
    const dialogRef = this.dialogService
      .open({
        title: 'Error',
        content: MessageFailureComponent,
        actions: [{ text: 'OK', primary: true }],
        width: 400,
        height: 250,
        minWidth: 250,
      });

    const messageInfo = dialogRef.content.instance;
    messageInfo.message = message;
    this.ngZone.run(() => {
      dialogRef.result.subscribe();
    });
  }


  ngOnInit(): void { }

  public ngAfterViewInit(): void {
    this.textbox.input.nativeElement.type = 'password';
  }

  public toggleVisibility(): void {
    const inputEl = this.textbox.input.nativeElement;
    this.passwordVisible = !this.passwordVisible;
    inputEl.type = this.passwordVisible ? 'text' : 'password';
  }
}
