import { Component, inject, OnInit, output } from '@angular/core';
import { SectorFacade } from '@app/adapters/sectors/sector.facade';
import { ProfileFacade } from '@app/adapters/profiles/profile.facade';
import { SearchService } from '@app/infrastructure/search/search.service';
import { FormBuilder, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { SearchFilters } from '@app/domain/search/search-filters';

interface SortOption {
  value: string;
  label: string;
}

@Component({
  selector: 'app-filter',
  standalone: true,
  imports: [FormsModule, ReactiveFormsModule],
  providers: [SectorFacade],
  templateUrl: './filter.component.html',
  styleUrl: './filter.component.scss',
})
export class FilterComponent implements OnInit {
  private readonly searchService = inject(SearchService);

  protected readonly sectorFacade = inject(SectorFacade);
  protected readonly sectors = this.sectorFacade.sectors;
  protected readonly profileFacade = inject(ProfileFacade);
  protected readonly profiles = this.profileFacade.profiles;

  readonly activeFilters = this.searchService.getFilters();

  onFilterChange = output<SearchFilters>();

  private fb = inject(FormBuilder);

  filterForm = this.fb.group({
    verified: [this.activeFilters().verified],
    secteur: [this.activeFilters().secteur],
    profession: [this.activeFilters().profession],
    sort: [this.activeFilters().sort || 'recent'],
  });

  onSubmit() {
    const filters = this.filterForm.getRawValue() as SearchFilters;
    this.searchService.setFilters(filters);
    this.onFilterChange.emit(filters);
  }

  sortOptions: SortOption[] = [
    { value: 'recent', label: 'Récents' },
    { value: 'name-asc', label: 'Nom (A-Z)' },
    { value: 'name-desc', label: 'Nom (Z-A)' },
    { value: 'verified', label: 'Vérifiés' },
  ];

  ngOnInit() {
    this.sectorFacade.load();
    this.profileFacade.load();
    this.initFormValues();
  }

  // Vérifier si des filtres sont actifs pour afficher le bouton "Effacer"
  hasActiveFilters(): boolean {
    const f = this.activeFilters();
    return f.verified || !!f.secteur || !!f.profession;
  }

  clearAllFilters(): void {
    this.searchService.reset();
    this.onFilterChange.emit(this.activeFilters());
    this.initFormValues();
  }

  private initFormValues() {
    const filters = this.searchService.getFilters();
    this.activeFilters.set(filters());

    this.filterForm.setValue({
      verified: this.activeFilters().verified,
      secteur: this.activeFilters().secteur,
      profession: this.activeFilters().profession,
      sort: this.activeFilters().sort || 'recent',
    });
  }
}
