import { HttpClientTestingModule } from '@angular/common/http/testing';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { ComponentFixture, discardPeriodicTasks, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { AvropService } from '@msfa-services/avrop.service';
import { of } from 'rxjs';
import { AvropFiltersComponent } from './avrop-filters.component';

describe('AvropFiltersComponent', () => {
  let component: AvropFiltersComponent;
  let fixture: ComponentFixture<AvropFiltersComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      imports: [HttpClientTestingModule],
      declarations: [AvropFiltersComponent],
      providers: [AvropService],
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(AvropFiltersComponent);
    component = fixture.componentInstance;
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should show 1 tag if filteredKommuner$ is an observable with one value', () => {
    component.filteredKommuner$ = of([{ id: '1', label: 'Stockholm', count: 1 }]);
    fixture.detectChanges();
    const tags = fixture.debugElement.queryAll(By.css('.avrop-filters__tag'));
    expect(tags.length).toBe(1);
  });

  it('clicking a kommun-tag should trigger removeKommun()', fakeAsync(() => {
    jest.spyOn(component, 'removeKommun').mockReturnThis();
    component.filteredKommuner$ = of([{ id: '1', label: 'Stockholm', count: 1 }]);
    fixture.detectChanges();
    const tags = fixture.debugElement.query(By.css('digi-tag'));
    tags.nativeElement.click();
    tick();
    fixture.detectChanges();
    expect(component.removeKommun).toHaveBeenCalled();
    discardPeriodicTasks();
  }));

  it('should show loading spinner when filters are loading', () => {
    fixture.detectChanges();
    const tags = fixture.debugElement.queryAll(By.css('msfa-loader'));
    expect(tags.length).toBe(1);
  });
});
