import { Component, effect, EventEmitter, Input, Output, signal } from '@angular/core';
import { SortState, TableColumn, DataTable } from '@shared/components/data-table/data-table';
import { ListParams, SortDir } from '@shared/paging/paging';
import { Agent } from 'src/app/core/interfaces/agent';
import { TpeDevice } from 'src/app/core/interfaces/tpe';
import { TpeService } from 'src/app/core/services/tpe';
import { Paginator } from "@shared/components/paginator/paginator";

@Component({
  selector: 'app-tpe-select',
  imports: [DataTable, Paginator],
  templateUrl: './tpe-select.html',
  styleUrl: './tpe-select.css',
})
export class TpeSelect {
  @Input() agent?: Agent; // Agent pour filtrer les TPE assignés
  @Input() selected: string[] = []; // Ids de TPE à cocher par défaut

  @Output() selectionChange = new EventEmitter<string[]>(); // TPE sélectionnés

  tpes = signal<TpeDevice[]>([]);
  total = signal(0);
  loading = signal<boolean>(true);
  selectedIds = signal<Set<string>>(new Set());
  page = signal(0);
  perPage = signal(10);
  search = signal('');
  sort = signal<SortState>({ key: 'id', dir: 'asc' });

 

  columns:TableColumn<TpeDevice>[] = [
    {
      key: 'numeroSerie',
      label: "Numero de serie"
    },
    {
      key: 'versionLogicielle',
      label: "Version du logiciel"
    },
    {
      key: 'modeleAppareil',
      label: "Model"
    },
    {
      key: 'systemeExploitation',
      label: 'Système d\'exploitation' 
    },
    {
      key: 'versionOs',
      label: 'Version Os'
    }
  ]

   constructor(private tpeService: TpeService) {
    effect(()=>{
      const params = {
        page: this.page(),
        size: this.perPage(), 
        sortKey: this.sort().key,
        sortDir: this.sort().dir as SortDir,
      }
      this.loadTpes(params);
    })
  }

  ngOnInit() {
    // Initialiser les TPE sélectionnés si fournis
    this.selectedIds.set(new Set(this.selected));
  }

  private loadTpes(params:ListParams) {
    this.loading.set(true);
    this.tpeService.list(params).subscribe({
      next: (res) => {
        // Filtrer : TPE non assignés ou déjà assignés à cet agent
        // console.log(res.content);
        const available = res.content.filter(
          (t) =>
            !t.assigned || t.agentConnecteId === this.agent?.id
        );
        this.tpes.set(available);
        this.total.set(res.pageable.total);
        this.loading.set(false);
      },
      error: (err) => {
        console.error(err);
        this.loading.set(false);
      },
    });
  }

  toggleTpe(tpe: TpeDevice) {
    const current = new Set(this.selectedIds());
    if (current.has(String(tpe.id))) {
      current.delete(String(tpe.id));
    } else {
      current.add(String(tpe.id));
    }
    this.selectedIds.set(current);
    this.selectionChange.emit(Array.from(current));
  }

  isChecked(tpe: TpeDevice) {
    return this.selectedIds().has(String(tpe.id));
  }

}
