import { createContext, useContext, useState, ReactNode } from "react";
import { Note } from "../models/Note"

type NotesStoreType = {
  notes: Map<string, Note>;
  createNote: () => void;
  updateNote: (noteId: string, changeset: Partial<Note>) => void;
  deleteNote: (noteId: string) => void;
  getNoteById: (noteId: string) => Note;
}

const NotesStore = createContext<NotesStoreType | null>(null);

export function NotesStoreProvider({ children }: { children: ReactNode }) {
  const [notes, setNotes] = useState<Map<string, Note>>(new Map<string, Note>());

  const createNote = () => {
    const newNote = new Note();
    setNotes(prev => new Map(prev.set(newNote.id, newNote)));
    return newNote;
  }

  const updateNote = (noteId: string, changeset: Partial<Note>) => {
    const noteToUpdate = notes.get(noteId)
    const updatedNote = new Note({ ...noteToUpdate, ...changeset })

    setNotes(prev => new Map(prev.set(noteId, updatedNote)));
  }

  const deleteNote = (noteId: string) => {
    notes.delete(noteId);
    setNotes(prev => new Map(prev))
  }

  const getNoteById = (noteId: string) => {
    return notes.get(noteId);
  }

  return (
    <NotesStore.Provider value={{ notes, createNote, updateNote, deleteNote, getNoteById }}>
      {children}
    </NotesStore.Provider>
  )
}

export function useNotesStore() {
  const context = useContext(NotesStore)
  if (!context) {
    throw new Error("useNotesStore must be used from within NotesStoreProvider")
  }

  return context;
}
