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

@Component({
  selector: 'app-note-detail',
  templateUrl: './note-detail.component.html',
  styleUrls: ['./note-detail.component.scss']
})
export class NoteDetailComponent implements OnInit {
  note: Note | undefined;

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

  ngOnInit(): void {
    this.route.paramMap.subscribe(params => {
      const id = params.get('id');
      if (id) {
        this.noteService.getNoteById(id).subscribe(
          (note) => {
            this.note = note;
          },
          (error) => {
            console.error('Error loading note:', error);
            this.router.navigate(['/notes']); // Redirect to list if note not found
          }
        );
      }
    });
  }

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

  deleteNote(): void {
    if (this.note && confirm('Are you sure you want to delete this note?')) {
      this.noteService.deleteNote(this.note.id).subscribe(
        () => {
          this.router.navigate(['/notes']);
        },
        (error) => {
          console.error('Error deleting note:', error);
        }
      );
    }
  }

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