// company-admin-list.component.ts
import { Component, OnInit, OnDestroy, ViewChild, ChangeDetectorRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule, FormsModule, FormControl } from '@angular/forms';
import { MatTableModule } from '@angular/material/table';
import { MatPaginatorModule, MatPaginator, PageEvent } from '@angular/material/paginator';
import { MatSortModule, MatSort, Sort } from '@angular/material/sort';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { Observable, Subject, BehaviorSubject } from 'rxjs';
import { debounceTime, distinctUntilChanged, map, startWith, takeUntil } from 'rxjs/operators';
import { CompanyAdminListService, AdminDetail } from './company-admin-list.service';

@Component({
  selector: 'app-company-admin-list',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    FormsModule,
    MatTableModule,
    MatPaginatorModule,
    MatSortModule,
    MatProgressBarModule,
    MatFormFieldModule,
    MatInputModule,
    MatButtonModule,
    MatIconModule
  ],
  templateUrl: './company-admin-list.component.html',
  styleUrl: './company-admin-list.component.scss'
})
export class CompanyAdminListComponent implements OnInit, OnDestroy {
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  // Observables
  admins$!: Observable<AdminDetail[]>;
  private _unsubscribeAll: Subject<any> = new Subject<any>();
  
  // Data
  private _admins: BehaviorSubject<AdminDetail[]> = new BehaviorSubject<AdminDetail[]>([]);
  filteredAdmins: AdminDetail[] = [];
  
  // UI State
  isLoading: boolean = false;
  selectedAdmin: AdminDetail | null = null;
  
  // Search
  searchInputControl: FormControl = new FormControl('');
  
  // Pagination
  pagination = {
    length: 0,
    page: 0,
    size: 10,
    pageSizeOptions: [5, 10, 25, 100]
  };

  constructor(
    private _adminService: CompanyAdminListService,
    private _changeDetectorRef: ChangeDetectorRef
  ) {}

  ngOnInit(): void {
    this.admins$ = this._admins.asObservable();

    // Search functionality
    this.searchInputControl.valueChanges
      .pipe(
        takeUntil(this._unsubscribeAll),
        debounceTime(300),
        distinctUntilChanged(),
        startWith('')
      )
      .subscribe(() => {
        this.filterAdmins();
      });

    // Load admin users
    this.loadAdmins();
  }

  ngOnDestroy(): void {
    this._unsubscribeAll.next(null);
    this._unsubscribeAll.complete();
  }

  /**
   * Load all admin users (Management, SuperAdmin, Admin)
   */
  loadAdmins(): void {
    this.isLoading = true;

    this._adminService.getAdminsWithDetails()
      .pipe(takeUntil(this._unsubscribeAll))
      .subscribe({
        next: (admins) => {
          this._admins.next(admins);
          this.pagination.length = admins.length;
          this.isLoading = false;
          this.filterAdmins();
          this._changeDetectorRef.markForCheck();
          
          console.log('Loaded admin users:', admins);
        },
        error: (error) => {
          console.error('Error loading admin users:', error);
          this.isLoading = false;
          this._changeDetectorRef.markForCheck();
        }
      });
  }

  /**
   * Filter admins based on search term
   */
  filterAdmins(): void {
    let admins = this._admins.getValue();
    const searchTerm = this.searchInputControl.value?.toLowerCase() || '';

    // Apply search filter
    if (searchTerm) {
      admins = admins.filter(admin =>
        admin.username.toLowerCase().includes(searchTerm) ||
        admin.email.toLowerCase().includes(searchTerm) ||
        admin.contact.includes(searchTerm) ||
        admin.roles.toLowerCase().includes(searchTerm) ||
        (admin.user_id && admin.user_id.toLowerCase().includes(searchTerm)) ||
        (admin.created_by_username && admin.created_by_username.toLowerCase().includes(searchTerm))
      );
    }

    // Update pagination
    this.pagination.length = admins.length;
    
    // Apply pagination
    const start = this.pagination.page * this.pagination.size;
    const end = start + this.pagination.size;
    this.filteredAdmins = admins.slice(start, end);

    this._changeDetectorRef.markForCheck();
  }

  /**
   * Sort admins
   */
  sortAdmins(sort: Sort): void {
    const admins = this._admins.getValue().slice();
    
    if (!sort.active || sort.direction === '') {
      this._admins.next(admins);
      this.filterAdmins();
      return;
    }

    const sortedAdmins = admins.sort((a, b) => {
      const isAsc = sort.direction === 'asc';
      switch (sort.active) {
        case 'user_id': return this.compare(a.user_id, b.user_id, isAsc);
        case 'username': return this.compare(a.username, b.username, isAsc);
        case 'email': return this.compare(a.email, b.email, isAsc);
        case 'contact': return this.compare(a.contact, b.contact, isAsc);
        case 'roles': return this.compare(a.roles, b.roles, isAsc);
        case 'user_status': return this.compare(a.user_status, b.user_status, isAsc);
        default: return 0;
      }
    });

    this._admins.next(sortedAdmins);
    this.filterAdmins();
  }

  /**
   * Compare function for sorting
   */
  private compare(a: string | number | undefined, b: string | number | undefined, isAsc: boolean): number {
    if (a === undefined || a === null) a = '';
    if (b === undefined || b === null) b = '';
    return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
  }

  /**
   * Handle pagination change
   */
  onPageChange(event: PageEvent): void {
    this.pagination.page = event.pageIndex;
    this.pagination.size = event.pageSize;
    this.filterAdmins();
  }

  /**
   * Handle sort change
   */
  onSortChange(sort: Sort): void {
    this.sortAdmins(sort);
  }

  /**
   * Toggle admin details
   */
  toggleDetails(adminId: number): void {
    if (this.selectedAdmin && this.selectedAdmin.id === adminId) {
      this.closeDetails();
      return;
    }

    const admin = this._admins.getValue().find(a => a.id === adminId);
    if (admin) {
      this.selectedAdmin = { ...admin };
      this._changeDetectorRef.markForCheck();
    }
  }

  /**
   * Close details panel
   */
  closeDetails(): void {
    this.selectedAdmin = null;
    this._changeDetectorRef.markForCheck();
  }

  /**
   * Refresh admin list
   */
  refreshAdmins(): void {
    this.loadAdmins();
  }

  /**
   * Get full file URL
   */
  getFullFileUrl(path: string | undefined): string | null {
    return this._adminService.getFullFileUrl(path);
  }

  /**
   * Track by function for ngFor
   */
  trackByFn(index: number, item: AdminDetail): any {
    return item.id || index;
  }
}