import { ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { of } from 'rxjs';
import { NoteListComponent } from '../note-list/note-list.component';
import { NoteService } from '../../services/note.service';
import { ClarityModule } from '@clr/angular';

describe('NoteListComponent', () => {
  let component: NoteListComponent;
  let fixture: ComponentFixture<NoteListComponent>;
  let noteServiceSpy: jasmine.SpyObj<NoteService>;

  const mockNotes = [
    { id: '1', title: 'Test Note 1', content: 'Content 1', createdAt: '2023-01-01', updatedAt: '2023-01-01' },
    { id: '2', title: 'Test Note 2', content: 'Content 2', createdAt: '2023-01-02', updatedAt: '2023-01-02' }
  ];

  beforeEach(async () => {
    noteServiceSpy = jasmine.createSpyObj('NoteService', ['getNotes', 'deleteNote']);
    noteServiceSpy.getNotes.and.returnValue(of(mockNotes));
    noteServiceSpy.deleteNote.and.returnValue(of(void 0));

    await TestBed.configureTestingModule({
      declarations: [ NoteListComponent ],
      imports: [ RouterTestingModule, ClarityModule ],
      providers: [ { provide: NoteService, useValue: noteServiceSpy } ]
    })
    .compileComponents();
  });

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

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

  it('should load notes on init', () => {
    expect(noteServiceSpy.getNotes).toHaveBeenCalled();
    expect(component.notes.length).toBe(2);
    expect(component.notes).toEqual(mockNotes);
  });

  it('should navigate to detail on viewNote', () => {
    const router = TestBed.inject(Router);
    spyOn(router, 'navigate');
    component.viewNote(mockNotes[0]);
    expect(router.navigate).toHaveBeenCalledWith(['/notes', mockNotes[0].id]);
  });

  it('should navigate to edit on editNote', () => {
    const router = TestBed.inject(Router);
    spyOn(router, 'navigate');
    component.editNote(mockNotes[0]);
    expect(router.navigate).toHaveBeenCalledWith(['/notes/edit', mockNotes[0].id]);
  });

  it('should delete note on deleteNote confirmation', () => {
    spyOn(window, 'confirm').and.returnValue(true);
    component.deleteNote(mockNotes[0]);
    expect(noteServiceSpy.deleteNote).toHaveBeenCalledWith(mockNotes[0].id);
  });

  it('should not delete note on deleteNote cancellation', () => {
    spyOn(window, 'confirm').and.returnValue(false);
    component.deleteNote(mockNotes[0]);
    expect(noteServiceSpy.deleteNote).not.toHaveBeenCalled();
  });
});
