import { Component, OnDestroy, OnInit, inject } from '@angular/core';
import { Router, ActivatedRoute, RouterModule } from '@angular/router';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { first } from 'rxjs/operators';

import { AuthenticationService } from '../user-services';

import { ConfirmationService } from 'primeng/api';
import { Subject, Subscription } from 'rxjs';
import { CommonModule } from '@angular/common';
import { CardModule } from 'primeng/card';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { ButtonModule } from 'primeng/button';
import { InputTextModule } from 'primeng/inputtext';

import { Utils } from '../shares';
@Component({
    templateUrl: './login.html',
    styleUrl: './login.css',
    selector: 'login',
    imports: [FormsModule, ReactiveFormsModule, ButtonModule, InputTextModule,
        RouterModule, CommonModule, CardModule],
    
})
export class Login implements OnInit, OnDestroy {
  loginForm: FormGroup;
  confirmationService = inject(ConfirmationService);
  route = inject(ActivatedRoute);
  router = inject(Router);
  authenticationService = inject(AuthenticationService);
  formBuilder = inject(FormBuilder);
  loading = false;
  homeUrl = "/person";
  submitted = false;
  isChange = true; // disable use false//true for not disable. make sure it true is disable button. 
  subChanged$ = new Subject<boolean>();
  // get return url from route parameters or default to '/'
  returnUrl = this.route.snapshot.queryParams['returnUrl'] || this.homeUrl;
  error = '';
  private subscription: Subscription = new Subscription();

  constructor() {

    this.loginForm = this.formBuilder.group({
      username: ['kham.vilaythong@gmail.com', Validators.required],
      password: ['password', Validators.required],

    });
  }

  ngOnInit() {
    // reset login status
    this.loading = false;
    this.subscription.add(this.loginForm.valueChanges.subscribe((x: any) => this.isChange = false));
    this.subscription.add(this.subChanged$.subscribe(x => this.isChange = x));

  }

  updateData($event: Event) {
    console.log("onChange click", $event);
  }

  // convenience getter for easy access to form fields
  get f() { return this.loginForm.value; }
  get isFieldsChange() {
    const chan = this.isChange || !this.loginForm.valid; // this disable so need true valid = true not
    //console.log(this.msg + 'is fields change', chan);
    return chan;
  }
  onSubmit() {

    //this.playAudio();

    // stop here if form is invalid
    if (this.loginForm.invalid) {
      return;
    }
    const fvalue = this.loginForm.value;
    this.loading = true;
    this.error = "";
    let username = "";
    let password = "";
    if (fvalue.username != null)
      username = fvalue.username;
    if (fvalue.password != null)
      password = fvalue.password;
    this.authenticationService.login(username, password)
      .pipe(first())
      .subscribe({
        next: (x: any) => {
          this.loading = false;
          console.log("login result ", x.data, this.returnUrl);
          if (x.statusCode == 1) {
            // if (x.data.role == 1) {
            //   this.homeService.reportDate = Utils.getLastMonth();
            // this.router.navigate(['/addkpi/' + x.data.id + '/' + x.data.measureId], { queryParams: { returnUrl: '/login' } });

            // }
            // else if (x.data.role == 3) {
            //  this.homeService.reportDate = Utils.getLastMonth();
            //    this.router.navigate(['/approval/' + x.data.id], { queryParams: { returnUrl: '/login' } });

            //}
            // else
            this.router.navigate([this.homeUrl]);
          }
          else {
            this.loginForm.patchValue({ password: '' });
            //  alert("Invalid Username or Password. Please try again.");
            console.error("error in login", x);
            this.confirmationService.confirm({
              message: 'Error in Login: Invalid username or password. May be your password is expired',
              header: 'Error Login',
              icon: 'pi pi-info-circle',
              rejectVisible: false,
              acceptLabel: 'OK',

            });
          }
        },
        error: er => {
          console.log("error in login", er);
          this.error = er.message;
          this.loading = false;
        }
      });

  }
  
  ngOnDestroy(): void {
    this.subscription.unsubscribe();
    this.loading = false;
  }

}
