import { Router } from '@angular/router';
import { NgClass } from '@angular/common';
import { NumericTextBoxComponent } from '@progress/kendo-angular-inputs';
import { DropDownListComponent } from '@progress/kendo-angular-dropdowns';
import { Component, OnInit, ViewChild, ElementRef, inject, computed } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { RowArgs, GridComponent, SelectionDirective, CheckboxColumnComponent, ColumnComponent } from '@progress/kendo-angular-grid';

import { AlertService } from '../components/alert';
import { EqualValidator } from '../customValidators';
import { BreadcrumbService } from '../breadcrumb.service';
import { UserService } from '../../providers/user/user.service.';
import { FunctionService } from '../components/models/function.service';
import { EmployeeControlComponent } from '../components/employeepicker/employeecontrol.component';

@Component({
  standalone: true,
  selector: 'new-user',
  templateUrl: './newuser.component.html',
  imports: [FormsModule, ReactiveFormsModule, NgClass, EmployeeControlComponent, DropDownListComponent, GridComponent, SelectionDirective, CheckboxColumnComponent, ColumnComponent, NumericTextBoxComponent]
})
export class NewUserComponent implements OnInit
{
  private readonly router = inject(Router);
  private readonly service = inject(UserService);
  private readonly fnSvc = inject(FunctionService);
  private readonly formBuilder = inject(FormBuilder);
  private readonly alertService = inject(AlertService);

  @ViewChild('loginId') private readonly loginId: ElementRef;

  public setting: any;
  public items: any[] = [];
  public required: string = '';
  public newuserForm: FormGroup;
  public canAdd: boolean = false;
  public loading: boolean = false;
  public submitted: boolean = false;
  public selectedIds: number[] = [];
  public fieldTextType1: boolean = false;
  public fieldTextType2: boolean = false;
  public selectedKeys(context: RowArgs): number { return context.dataItem.groupId; };
  public authMethods: Array<{ id: number, value: string }> = [{ id: 0, value: 'None' }, { id: 1, value: 'Email' }, { id: 2, value: 'Mobile SMS' }, { id: 3, value: 'Third Party Authenticator' }];

  private settingApplied: boolean = false;

  constructor()
  {
    const bcService = inject(BreadcrumbService);
    bcService.setItems([{ label: 'System Setup' }, { label: 'User Management' }, { label: 'Users', routerLink: ['/users'] }, { label: 'New User', routerLink: ['/newuser'] }]);
    if (!this.service.currentUserValue)
    {
      this.router.navigate(['/login']);
      return;
    }

    const navigated = computed(() => this.router.currentNavigation())();
    this.setting = navigated?.extras?.state?.setting;

    this.canAdd = this.service.currentUserValue?.moduleIds?.includes('ELIT.1.2.2_1');
  }

  ngOnInit(): void
  {
    this.newuserForm = this.formBuilder.group(
      {
        loginId: '',
        isEmployee: false,
        employeeId: { value: null, disabled: true },
        username: '',
        designation: '',
        mobileNo: '',
        emailAddress: '',
        seqId: 1,
        viewToAll: false,
        canUseAtnSys: true,
        password: ['', Validators.required],
        confirmPassword: ['', Validators.required],
        dbOnStartup: false,
        daMultiLogin: false,
        status: true,
        neverExpire: { value: false, disabled: true },
        accessStatus: true,
        authReqAtlogin: false,
        authMethod: { value: 0, disabled: true },
      },
      {
        validators: EqualValidator('password', 'confirmPassword')
      }
    );
    this.setValidatorsToControls();

    this.loadGroups();
  }

  private setValidatorsToControls(): void
  {
    if (!this.settingApplied && this.setting && this.newuserForm?.controls)
    {
      this.settingApplied = true;
      this.fnSvc.setValidatorsToToControl({ control: this.f.loginId, required: this.setting.label01Req, regExp: this.setting.label01RegExp, minLen: 3, maxLen: 30 });
      this.fnSvc.setValidatorsToToControl({ control: this.f.username, required: this.setting.label02Req, regExp: this.setting.label02RegExp, minLen: 3, maxLen: 75 });
      this.fnSvc.setValidatorsToToControl({ control: this.f.mobileNo, required: this.setting.label03Req, regExp: this.setting.label03RegExp, minLen: 0, maxLen: 15 });
      this.fnSvc.setValidatorsToToControl({ control: this.f.emailAddress, required: this.setting.label04Req, regExp: this.setting.label04RegExp, minLen: 0, maxLen: 100 });
      this.fnSvc.setValidatorsToToControl({ control: this.f.designation, required: this.setting.label19Req, regExp: this.setting.label19RegExp, minLen: 0, maxLen: 50 });
      this.fnSvc.setValidatorsToToControl({ control: this.f.seqId, required: this.setting.label26Req, regExp: this.setting.label26RegExp, minValue: 1, maxValue: 999999 });
    }
  }

  public loadGroups(): void
  {
    const params = { criteria: '', status: 8 };
   
  }

  public toggleFieldType(controlId): void
  {
    if (controlId === 1)
      this.fieldTextType1 = !this.fieldTextType1;
    else if (controlId === 2)
      this.fieldTextType2 = !this.fieldTextType2;
  }

  public isEmployeeCheckChanged(): void
  {
    if (this.f.isEmployee.value)
    {
      this.f.employeeId.enable();
      this.f.username.disable();
      this.f.designation.disable();
      this.f.mobileNo.disable();
      this.f.emailAddress.disable();
    }
    else
    {
      this.f.employeeId.disable();
      this.f.username.enable();
      this.f.designation.enable();
      this.f.mobileNo.enable();
      this.f.emailAddress.enable();
    }
  }

  public onEmployeeSelected(event: any): void
  {
    if (event?.employeeId)
    {
      this.newuserForm.patchValue(
        {
          username: event.name,
          mobileNo: event.contactNo,
          designation: event.designation,
          emailAddress: event.emailAddress
        });
    }
    else
    {
      this.newuserForm.patchValue(
        {
          username: '',
          mobileNo: '',
          designation: '',
          emailAddress: '',
        });
    }
  }

  public eventCheck(event: any, controlId: number): void
  {
    if (controlId === 1)
    {
      if (event?.target?.checked)
      {
        this.newuserForm.get('accessStatus').disable()
        this.newuserForm.get('accessStatus').setValue(false);
      }
      else
      {
        this.newuserForm.get('accessStatus').enable()
      }
    }
    else if (controlId === 2)
    {
      if (event?.target?.checked)
      {
        this.newuserForm.get('neverExpire').disable()
        this.newuserForm.get('neverExpire').setValue(false);
      }
      else
      {
        this.newuserForm.get('neverExpire').enable()
      }
    }
    else if (controlId === 3)
    {
      this.required = '';
      if (event?.target?.checked)
      {
        this.required = 'required';
        this.newuserForm.get('authMethod').enable()
      }
      else
      {
        this.newuserForm.get('authMethod').setValue(0);
        this.newuserForm.get('authMethod').disable()
      }
    }
  }

  public keyPressEvent(event: any): boolean
  {
    return this.fnSvc.validateNumbers({ event: event, includePlus: true });
  }

  get f() { return this.newuserForm.controls; }

  public onSubmit(): void
  {
    this.submitted = true;
    this.alertService.clear();
    if (this.newuserForm.invalid)
      return;

    this.loading = true;
    const params: any =
    {
      loginId: this.f.loginId.value,
      employeeId: this.f.employeeId.value?.employeeId,
      employeeCode: this.f.employeeId.value?.code,
      password: this.f.password.value,
      userName: this.f.username.value,
      designation: this.f.designation.value,
      mobileNo: this.f.mobileNo.value,
      emailAddress: this.f.emailAddress.value,
      seqId: +(this.f.seqId.value ?? '1'),
      viewToAll: this.f.viewToAll.value,
      canUseAttendanceSystem: this.f.canUseAtnSys.value,
      dbOnStartup: this.f.dbOnStartup.value,
      disallowMultiLogin: this.f.daMultiLogin.value,
      status: (this.f.status.value ? 8 : 16),
      neverExpire: this.f.neverExpire.value,
      accessStatus: this.f.accessStatus.value ? 1 : 3,
      authReqAtlogin: this.f.authReqAtlogin.value,
      authMethod: this.f.authReqAtlogin.value ? +(this.f.authMethod.value || '0') : 0,
      groupIds: this.selectedIds
    };

    this.service.addUser(params).subscribe(
      {
        next: (resp: any) =>
        {
          this.loading = false;
          if (resp.returnStatus === 200)
          {
            this.newuserForm.reset(
              {
                loginId: '',
                status: true,
                username: '',
                mobileNo: '',
                password: '',
                designation: '',
                emailAddress: '',
                employeeId: null,
                isEmployee: false,
                dbOnStartup: false,
                confirmPassword: '',
                canUseAtnSys: true,
                daMultiLogin: false,
                authReqAtlogin: false,
                authMethod: { value: 0, disabled: true },
                neverExpire: { value: false, disabled: true },
                accessStatus: { value: true, disabled: false },
                seqId: (parseInt(this.f.seqId.value ?? '1') + 1)
              }
            );
            this.isEmployeeCheckChanged();
            if (this.loginId?.nativeElement)
              this.loginId.nativeElement.focus();

            this.selectedIds = [];
            this.alertService.info(resp.returnMessage);
            this.submitted = false;
          }
          else
          {
            this.alertService.error(resp.returnMessage);
          }
        },
        error: (errorMessage: string) =>
        {
          this.loading = false;
          this.alertService.error(errorMessage);
        }
      });
  }
}
