import { CommonModule } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { NgSelectModule } from '@ng-select/ng-select';
import { TranslateModule } from '@ngx-translate/core';
import { pageSizeOptions } from '../../utils/app.constants';
import { SetupUser } from '../../models/user';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { ButtonManagementService } from '../../services/button-management.service';
import { StorageService } from '../../shared/services/storage.service';
import { TableFilterPipe } from '../../shared/pipes/table-filter.pipe';
import { URIKey } from '../../utils/uri-enums';
import { HttpErrorResponse, HttpParams } from '@angular/common/http';
import { HttpURIService } from '../../app.http.uri.service';
import { I18NService } from '../../services/i18n.service';
import { SuccessMessages } from '../../utils/enums';



@Component({
  selector: 'app-setup-user',
  standalone: true,
  imports: [TranslateModule, ReactiveFormsModule, FormsModule, CommonModule, NgSelectModule, TableFilterPipe],
  templateUrl: './setup-user.component.html',
  styleUrl: './setup-user.component.scss'
})
export class SetupUserComponent implements OnInit {
  userForm!: FormGroup;
  showForm = false;
  selectedUserId!: any;
  showDeleteModal = false;
  userIdToDelete: any = null;
  allItems: SetupUser[] = [];
  currentPage: number = 1;
  pageSizeOptions = pageSizeOptions
  itemsPerPage: number = 5;
  pagedItems: any[] = [];
  searchText: any = '';
  renewalDataExpanded: boolean = true;
  totalCount: number = 0;
  mode: 'edit' | 'view' = 'view';

  userSetupDataExpanded: boolean = true
  buttonPermissions: any;
    isLoading: boolean = false;
    setupUserList: SetupUser[] = [];
  roleOptions = [
    { label: 'Admin', value: 'ADMIN' },
    { label: 'User', value: 'USER' }
  ];


  constructor(
    private fb: FormBuilder,
    private buttonManagementService: ButtonManagementService,
    private storageService: StorageService,
    private httpService: HttpURIService,
    private i18nService: I18NService
  ){}

  onSearch(value: string): void {
    this.searchText = value;
  }

  totalPages(): number {
    return Math.ceil(this.allItems.length / this.itemsPerPage);
  }

  previousPage(): void {
    if (this.currentPage > 1) {
      this.currentPage--;
    }
  }

  nextPage(): void {
    if (this.currentPage < this.totalPages()) {
      this.currentPage++;
    }
  }

  itemsPerPageChanged(): void {
    this.currentPage = 1;
    this.updatePagedItems();
  }
  onSubmit() {
    if (this.userForm.invalid) {
      this.userForm.markAllAsTouched();
      return;
    }

    const newUser : SetupUser = {
      userId: this.userForm.value.userId,
      userFullname: this.userForm.value.userFullname,
      email: this.userForm.value.email,
      role: this.userForm.value.userRole,
      porOrgacode: this.storageService.getItem('POR_ORGACODE'),
      password: this.userForm.value.defaultPassword
    }

    this.httpService.requestPOST<SetupUser[]>(URIKey.CREATE_USER, newUser).subscribe({
      next: (response) => {
        if (!(response instanceof HttpErrorResponse)) {
          this.i18nService.success(SuccessMessages.USER_CREATED_SUCCESS, []);
          this.userForm.reset();
          this.mode = 'edit';
          this.loadUsersDirect()
        }
    }
    });


    
  }
  updatePagedItems(): void {
  const startIndex = (this.currentPage - 1) * this.itemsPerPage;
  const endIndex = startIndex + this.itemsPerPage;
  this.pagedItems = this.allItems.slice(startIndex, endIndex);
}

  getButtonPermissions(){
    this.buttonPermissions = this.buttonManagementService.buttonPermissions["setupUser"];
  }

  toggleTableCard(): void {
  this.userSetupDataExpanded = !this.userSetupDataExpanded;
}
  
ngOnInit(): void {

  this.getButtonPermissions();

   this.userForm = this.fb.group({
      userId: ['', [
        Validators.required,
        Validators.minLength(5),
        Validators.pattern(/^\S+$/)
      ]
    ],
      userFullname: ['', [
        Validators.required,
        Validators.minLength(5),
        Validators.pattern(/^\S+$/)
      ]
    ],
      defaultPassword: ['', [
        Validators.required,
        Validators.pattern(
        /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,20}$/
      )
      ]
    ],
      email: ['', [Validators.required, Validators.email]],
      userRole: [null, Validators.required]
    });  
  this.loadUsersDirect(); 
  }

  loadUsersDirect(): void {
    this.isLoading = false;
     let params = new HttpParams()
    .set('page', this.currentPage.toString())
    .set('size', this.itemsPerPage.toString());
  
    this.httpService.requestGET<any[]>(URIKey.GET_ALL_USER_URI, params).subscribe({
      next: (response) => {
        this.setupUserList = response
        this.allItems = [...this.setupUserList]; 
        this.updatePagedItems();
        this.isLoading = false;
      },
      error: (err) => {
        console.error('Error fetching users:', err);
        this.allItems = [];
        this.isLoading = false;
      }
    });
  }

  onView(userId: any): void{
    let params = new HttpParams().set('userId', userId);
    this.httpService.requestGET<SetupUser>(URIKey.GET_USER_BY_ID, params).subscribe({
      next: (response: SetupUser) => {
        this.userForm.patchValue({
        userId: response.userId,
        userFullname: response.userFullname,
        email: response.email,
        userRole: response.role,
        defaultPassword: '' 
      });
      this.selectedUserId = userId;
      this.isLoading = false;
      },
      error: (err) => {
        console.error('Error fetching users:', err);
        this.allItems = [];
        this.isLoading = false;
      }
    });
  }

  onDelete(userId: any){
    let params = new HttpParams().set('userId', userId);
    this.httpService.requestDELETE<any>(URIKey.DELETE_USER, params).subscribe({
      next: (response) =>{
        if (!(response instanceof HttpErrorResponse)) {
        this.i18nService.success(SuccessMessages.USER_DELETE_SUCCESS, []);
        this.loadUsersDirect();
        this.userForm.reset();
        this.selectedUserId = null;
      }

      }
    })
  }

}
