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 searchTextSubject = new BehaviorSubject<string>('');
  private itemsPerPageSubject = new BehaviorSubject<number>(5);
  private paginatedUsersSubject = new BehaviorSubject<SetupUser[]>([]);
  users$ = this.usersSubject.asObservable();
  currentPage$ = this.currentPageSubject.asObservable();
  totalCount$ = this.totalCountSubject.asObservable();
  searchText$ = this.searchTextSubject.asObservable();
  itemsPerPage$ = this.itemsPerPageSubject.asObservable();
  paginatedUsers$ = this.paginatedUsersSubject.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);
              this.applyPagination(); 
            },
            error: (err) => console.error(err)
          });
      }
    });
  }

  private applyPagination(): void {
    const allUsers = this.usersSubject.value;
    const searchText = this.searchTextSubject.value.toLowerCase();
    const currentPage = this.currentPageSubject.value;
    const itemsPerPage = this.itemsPerPageSubject.value;

    let filtered = allUsers.filter(user =>
      user.userId.toLowerCase().includes(searchText) ||
      user.userFullname.toLowerCase().includes(searchText) ||
      user.email.toLowerCase().includes(searchText)
    );

    const totalCount = filtered.length;
    const startIndex = (currentPage - 1) * itemsPerPage;
    const paginatedUsers = filtered.slice(startIndex, startIndex + itemsPerPage);

    this.paginatedUsersSubject.next(paginatedUsers);
    this.totalCountSubject.next(totalCount);
  }

  setSearchText(searchText: string): void {
    this.searchTextSubject.next(searchText);
    this.currentPageSubject.next(1);
    this.applyPagination();
  }

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

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

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

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

  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)
}

}