import { Component, OnInit } from '@angular/core';
import { NoteService } from '../../../../services/note.service';
import { Note } from '../../../../models/note.model';
import { Router } from '@angular/router';

@Component({
  selector: 'app-note-list',
  templateUrl: './note-list.component.html',
  styleUrls: ['./note-list.component.scss']
})
export class NotesListComponent implements OnInit {
  notes: Note[] = [];
  loading: boolean = true;
  error: string | null = null;

  constructor(private noteService: NoteService, private router: Router) { }

  ngOnInit(): void {
    this.loadNotes();
  }

  loadNotes(): void {
    this.loading = true;
    this.error = null;
    this.noteService.getAllNotes().subscribe({
      next: (data) => {
        this.notes = data;
        this.loading = false;
      },
      error: (err) => {
        this.error = 'Failed to load notes. Please try again later.';
        this.loading = false;
        console.error('Error loading notes:', err);
      }
    });
  }

  viewNote(id: number): void {
    this.router.navigate(['/notes', id]);
  }

  editNote(id: number): void {
    this.router.navigate(['/notes/edit', id]);
  }

  deleteNote(id: number): void {
    if (confirm('Are you sure you want to delete this note?')) {
      this.noteService.deleteNote(id).subscribe({
        next: () => {
          this.notes = this.notes.filter(note => note.id !== id);
        },
        error: (err) => {
          this.error = 'Failed to delete note. Please try again later.';
          console.error('Error deleting note:', err);
        }
      });
    }
  }

  createNewNote(): void {
    this.router.navigate(['/notes/new']);
  }
}