import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Note } from '../../models/note.model';

@Component({
  selector: 'app-note-form',
  templateUrl: './note-form.component.html',
  styleUrls: ['./note-form.component.scss']
})
export class NoteFormComponent implements OnInit {
  @Input() note: Note | null = null;
  @Output() saveNote = new EventEmitter<Note>();
  @Output() cancel = new EventEmitter<void>();

  noteForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.noteForm = this.fb.group({
      title: ['', [Validators.required, Validators.maxLength(100)]],
      content: ['']
    });
  }

  ngOnInit(): void {
    if (this.note) {
      this.noteForm.patchValue(this.note);
    }
  }

  onSubmit(): void {
    if (this.noteForm.valid) {
      const noteToSave: Note = {
        ...this.note, // Keep existing id, createdAt, updatedAt if editing
        ...this.noteForm.value,
        updatedAt: new Date().toISOString() // Update updatedAt on save
      };
      this.saveNote.emit(noteToSave);
    }
  }

  onCancel(): void {
    this.cancel.emit();
  }
}
