import { Component, EventEmitter, OnInit, Output, TemplateRef, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AbstractControl, UntypedFormBuilder, UntypedFormGroup, ValidationErrors, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { AuthenticationService } from 'src/app/core/services/auth.service';
import { UserProfileService } from 'src/app/core/services/user.service';
import { first } from 'rxjs/operators';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { BaseService } from 'src/app/shared/service/base.service';
import { ToastService } from 'src/app/toast/toast-service';
import { RoleService } from '../../rolelist/role.service';
import { StorageService } from 'src/app/shared/service/storage.service';


@Component({
  selector: 'app-add-user',
 
  templateUrl: './add-user.component.html',
  styleUrl: './add-user.component.scss'
})

export class AddUserComponent implements OnInit{
  @ViewChild('scrollDataModal', { static: true }) scrollDataModal: TemplateRef<any>;

  @Output() UserAdded = new EventEmitter<void>();

  adduserfrom: UntypedFormGroup;
  submitted = false;
  error = '';
  successmsg = false;
  tenants:any;
  selectedTenant:any

  passwordVisible = false;

  passwordValid: boolean = false;


  showPasswordTooltip: boolean = false;
  passwordLengthValid: boolean = false;
  passwordUpperCaseValid: boolean = false;
  passwordLowerCaseValid: boolean = false;
  passwordNumberValid: boolean = false;
  passwordSpecialCharValid: boolean = false;


  constructor(private formBuilder: UntypedFormBuilder, 
    private route: ActivatedRoute, 
    private router: Router, 
    private authenticationService: AuthenticationService,
    private userService: UserProfileService,
    private modalService: NgbModal,
    public baseService: BaseService,
    public toastService: ToastService,
    public roleService:RoleService,
    private storrage:StorageService
  ) { }

    ngOnInit() {
      document.body.setAttribute('class', 'authentication-bg');

      this.roleService.tenant$.subscribe(data => {
        this.tenants = data;
      });
    }
    passwordValidator(control: AbstractControl): Promise<ValidationErrors | null> {
      return new Promise((resolve, reject) => {
        // Your validation logic here
        if (control.value && control.value.length < 8) {
          resolve({ minlength: true });
        } else if (!/[A-Z]/.test(control.value)) {
          resolve({ uppercase: true });
        } else if (!/[a-z]/.test(control.value)) {
          resolve({ lowercase: true });
        } else if (!/\d/.test(control.value)) {
          resolve({ number: true });
        } else if (!/[!@#$%^&*(),.?":{}|<>]/.test(control.value)) {
          resolve({ specialCharacter: true });
        } else {
          resolve(null);
        }
      });
    }

    SaveTenantUser(userid:any){

      if(this.selectedTenant!=null)
      {
      const formData = new URLSearchParams();
      formData.append('userId', userid);
      formData.append('tenantId', this.selectedTenant.tenantUUID);

      this.baseService.postData('tenants/saveTenantUser', formData).subscribe(
        (data: any) => {
          if (data) {
            // task to be done add aothe valu as attributes
            this.successmsg = true;
            // You can also close the modal here if needed
            this.modalService.dismissAll();
            // Reset the form
            this.adduserfrom.reset();

            this.UserAdded.emit();
            
            // Set the form as not submitted
            this.submitted = false;
            this.toastService.show('User added successfully!', { classname: 'bg-success text-light', delay: 3000 });
          }
        },
        (err) => {
          console.log(err);
        }
        );
      }
      else if("Tenant Admin"==this.storrage.getItem('role')){

        const loginuserid=this.storrage.getItem('user');

        this.baseService.getData(`tenants/getbyuserid/${loginuserid}`).subscribe(
          (data: any) => {
            if (data) {
              console.log(data);
              const tenantuuid=data.data[0].tenantUUID;
              const formData = new URLSearchParams();
              formData.append('userId', userid);
              formData.append('tenantId', tenantuuid);
        
              this.baseService.postData('tenants/saveTenantUser', formData).subscribe(
                (data: any) => {
                  if (data) {
                    // task to be done add aothe valu as attributes
                    this.successmsg = true;
                    // You can also close the modal here if needed
                    this.modalService.dismissAll();
                    // Reset the form
                    this.adduserfrom.reset();

                    this.UserAdded.emit();
                    
                    // Set the form as not submitted
                    this.submitted = false;
                    this.toastService.show('User added successfully!', { classname: 'bg-success text-light', delay: 3000 });
                  }
                },
                (err) => {
                  console.log(err);
                }
              );
            }
          },
          (err) => {
            console.log(err);
          }
        );
      }

    }
  
    hasRole(role:string){
      if(role==this.storrage.getItem('role'))
      {
        return true;
      }
      else{
        return false;
      }
  
    }

    ngAfterViewInit() {
    }

    get f() { return this.adduserfrom.controls; }

    get emailControl() {
      return this.adduserfrom.get('email'); // Access the email control
    }
  
    get userControl(){
      return this.adduserfrom.get('username'); 
    }
    get passwordControl(){
      return this.adduserfrom.get('password'); 
    }
    get lastnameControl(){
      return this.adduserfrom.get('lastname'); 
    }
    get firstnameControl(){
      return this.adduserfrom.get('firstname'); 
    }

    onUsernameChange(event: any) {
      const input = event.target.value;
      event.target.value = input.replace(/\s+/g, ''); // Remove whitespace
    }

    onSubmit() {
      this.submitted = true;
      if (this.adduserfrom.invalid) {
        return;
      }
      console.log(this.adduserfrom.getRawValue());
      const formData = new URLSearchParams();
      formData.append('email', this.adduserfrom.get('email').value);
      formData.append('username', this.adduserfrom.get('username').value);
      formData.append('name', this.adduserfrom.get('firstname').value);

      formData.append('lastName', this.adduserfrom.get('lastname').value);
      formData.append('password', this.adduserfrom.get('password').value);

      this.baseService.postData('user/addUser', formData).subscribe(
        (data: any) => {
          if (data) {
          console.log(data);

          this.SaveTenantUser(data.UserID)
          
          
          }
        },
        (err) => {
          console.log(err);
          this.toastService.show('User not added please check the paramter!', { classname: 'bg-error text-light', delay: 3000 });
        }
        );

    }
    togglePasswordVisibility() {
      this.passwordVisible = !this.passwordVisible;
    }
    checkPassword() {
      const password = this.adduserfrom.get('password').value;
      this.passwordLengthValid = password.length >= 8;
      this.passwordUpperCaseValid = /[A-Z]/.test(password);
      this.passwordLowerCaseValid = /[a-z]/.test(password);
      this.passwordNumberValid = /[0-9]/.test(password);
      this.passwordSpecialCharValid = /[!@#$%^&*(),.?":{}|<>]/.test(password);
      this.passwordValid = this.passwordLengthValid && this.passwordUpperCaseValid && this.passwordLowerCaseValid && this.passwordNumberValid && this.passwordSpecialCharValid;
    }
    openModal() {
      this.modalService.open(this.scrollDataModal, { scrollable: true ,windowClass:'modal-holder', centered: true, backdrop: "static"});

      this.adduserfrom = this.formBuilder.group({
       
        username:['',Validators.required],
        lastname:['', Validators.required],
        firstname:['', Validators.required],
        email: ['', [Validators.required, Validators.email]],
        password: ['', Validators.required,this.passwordValidator.bind(this)],
      });
    }
}
