import { create } from 'zustand';
import { getNote, listNotes, type MobileNote } from '../api/notes';

export type NotesState = {
  notes: MobileNote[];
  selectedNote: MobileNote | null;
  isLoading: boolean;
  hydrate: () => Promise<void>;
  openNote: (id: string) => Promise<void>;
  saveDraft: (title: string, body: string) => void;
  updateNote: (id: string, title: string, body: string) => void;
};

export const useNotesStore = create<NotesState>((set, get) => ({
  notes: [],
  selectedNote: null,
  isLoading: false,
  async hydrate() {
    set({ isLoading: true });
    const notes = await listNotes();
    set({ notes, isLoading: false });
  },
  async openNote(id: string) {
    set({ isLoading: true });
    const note = await getNote(id);
    set({ selectedNote: note, isLoading: false });
  },
  saveDraft(title: string, body: string) {
    const draft: MobileNote = {
      id: `draft-${Date.now()}`,
      title: title.trim() || 'Untitled draft',
      body,
      workspaceName: 'Drafts',
    };

    set({ notes: [draft, ...get().notes], selectedNote: draft });
  },
  updateNote(id: string, title: string, body: string) {
    const nextTitle = title.trim() || 'Untitled draft';
    const current = get().notes.find((note: MobileNote) => note.id === id);

    if (!current) {
      return;
    }

    const updated: MobileNote = {
      ...current,
      title: nextTitle,
      body,
    };

    set({
      notes: get().notes.map((note: MobileNote) => (note.id === id ? updated : note)),
      selectedNote: updated,
    });
  },
}));
