import { Injectable } from '@angular/core';
import { SetupUser } from '../models/user';
import { BehaviorSubject, Observable } from 'rxjs';
import { URIKey } from '../utils/uri-enums';
import { URIService } from '../app.uri';
import { HttpURIService } from '../app.http.uri.service';
import { HttpParams } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class UserSetupService {
  private usersSubject = new BehaviorSubject<SetupUser[]>([]);
  private currentPageSubject = new BehaviorSubject<number>(1);
  private totalCountSubject = new BehaviorSubject<number>(0);
  private itemsPerPageSubject = new BehaviorSubject<number>(5);
  users$ = this.usersSubject.asObservable();
  currentPage$ = this.currentPageSubject.asObservable();
  totalCount$ = this.totalCountSubject.asObservable();
  itemsPerPage$ = this.itemsPerPageSubject.asObservable();

  constructor(private httpURIService: HttpURIService, private uriService: URIService) { }

loadUsers(): void {
    this.uriService.canSubscribe.subscribe(can => {
      if (can) {
        this.httpURIService
          .requestGET<any>(URIKey.GET_ALL_USERS)
          .subscribe({
            next: (res) => {
              const users = Array.isArray(res) ? res : res?.data;
              this.usersSubject.next(users ?? []);
              this.totalCountSubject.next(users.length);
              
            },
            error: (err) => console.error(err)
          });
      }
    });
  }

  setItemsPerPage(itemsPerPage: number): void {
    this.itemsPerPageSubject.next(itemsPerPage);
    this.currentPageSubject.next(1);
   
  }

  nextPage(): void {
    const totalPages = this.getTotalPages();
    const currentPage = this.currentPageSubject.value;
    if (currentPage < totalPages) {
      this.currentPageSubject.next(currentPage + 1);
    }
  }

  previousPage(): void {
    const currentPage = this.currentPageSubject.value;
    if (currentPage > 1) {
      this.currentPageSubject.next(currentPage - 1);
    
    }
  }

  goToPage(page: number): void {
    const totalPages = this.getTotalPages();
    if (page > 0 && page <= totalPages) {
      this.currentPageSubject.next(page);
      
    }
  }

  getTotalPages(): number {
    const totalCount = this.totalCountSubject.value;
    const itemsPerPage = this.itemsPerPageSubject.value;
    return Math.ceil(totalCount / itemsPerPage);
  }
 
  addUser(payload: SetupUser): Observable<SetupUser> {
  return this.httpURIService.requestPOST<SetupUser>(URIKey.CREATE_USER, payload);
}


getUserById(userId: any){
  const params = new HttpParams().set('userId', userId)
  
  return this.httpURIService.requestGET(URIKey.GET_USER_BY_ID, params);
}

deleteUser(userId: any){
  const params = new HttpParams().set('userId', userId)
  console.log("params success",params)
  return this.httpURIService.requestDELETE(URIKey.DELETE_USER, params)
}

}