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 { UserSetupService } from '../../services/user-setup.service';
import { UserFilterPipe } from '../../shared/pipes/userFilterPipe';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';


@Component({
  selector: 'app-setup-user',
  standalone: true,
  imports: [TranslateModule, ReactiveFormsModule, FormsModule, CommonModule, NgSelectModule, UserFilterPipe],
  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;
  searchText: string = '';
  renewalDataExpanded: boolean = true;
  totalCount: number = 0;
  mode: 'edit' | 'view' = 'view';


  constructor(private userService: UserSetupService, private fb: FormBuilder){}

  get users$(){
    return this.userService.users$;
  }
  onSearch(value: string): void {
  this.searchText = value;
}

  onPageSizeChange(pageSize: number): void {
    this.userService.setItemsPerPage(pageSize);
  }

  nextPage(): void {
    this.userService.nextPage();
  }

  previousPage(): void {
    this.userService.previousPage();
  }
  

  getTotalPages(): number {
    return this.userService.getTotalPages();
  }
  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.userId}@dummy.com`,
      role: 'ADMIN',
      defaultPassword: this.userForm.value.defaultPassword
    }
    this.userService.addUser(newUser).subscribe({
      next: () => {
        this.userService.loadUsers();
      this.userService.loadUsers();
      this.userForm.reset(); 
      this.mode = 'edit';
      },
      error: (err: any) => console.error(err)
    });


    
  }
  onView(userId: any){
    this.mode = 'view';
    this.showForm = true;
    this.selectedUserId = userId;
    this.userService.getUserById(userId).subscribe((user: any)=>{
      this.userForm.patchValue({
        userId : user.userId,
        userFullname : user.userFullname,
        defaultPassword : '',
      })
    })
  }

  onDelete(userId: any){
    this.userService.deleteUser(userId).subscribe({
      next: (res: any) => {
      this.userService.loadUsers();
      this.userForm.reset()
      this.selectedUserId = null;
      },
      error: (err:any) =>{
        console.log('user not deleted')
      }
      
    });

  }
  
ngOnInit(): void {
   this.userForm = this.fb.group({
      userId: ['', [Validators.required]],
      userFullname: ['', [Validators.required, Validators.maxLength(500)]],
      defaultPassword: ['', Validators.required]
    });  
  
  this.userService.loadUsers();

  this.userService.users$.subscribe((users: SetupUser[]) => {
      this.allItems = users;
    });
  this.userService.currentPage$.subscribe((page: number) => {
      this.currentPage = page;
    });
    this.userService.totalCount$.subscribe((count: number) => {
      this.totalCount = count;
    });
    this.userService.itemsPerPage$.subscribe((size: number) => {
      this.itemsPerPage = size;
    });
}

}
