import { ref } from 'vue'
import { api } from '../api/client'
import { useToast } from './useToast'
import type { NoteItem } from '../types'
import type { Ref } from 'vue'

export function useLiteratureNotes(pmid: number, notes: Ref<NoteItem[]>) {
  const toast = useToast()
  const noteContent = ref('')
  const noteSaving = ref(false)

  const showEditModal = ref(false)
  const editingNoteId = ref('')
  const editingContent = ref('')
  const editIsPrivate = ref(true)
  const editSaving = ref(false)

  async function handleAddNote() {
    if (!noteContent.value.trim()) return
    noteSaving.value = true
    try {
      const { data } = await api.post(`/notes/literature/${pmid}`, { content: noteContent.value })
      notes.value.unshift(data)
      noteContent.value = ''
    } catch (e) { toast.apiError(e, '保存笔记失败，请重试') } finally { noteSaving.value = false }
  }

  function handleOpenEdit(n: NoteItem) {
    editingNoteId.value = n.id
    editingContent.value = n.content
    editIsPrivate.value = n.is_private !== false
    showEditModal.value = true
  }

  async function handleSaveEdit() {
    if (!editingContent.value.trim()) { toast.warning('笔记内容不能为空'); return }
    editSaving.value = true
    try {
      const { data } = await api.put(`/notes/${editingNoteId.value}`, { content: editingContent.value, is_private: editIsPrivate.value })
      const idx = notes.value.findIndex((n: NoteItem) => n.id === editingNoteId.value)
      if (idx !== -1) notes.value[idx] = data
      showEditModal.value = false
      toast.success('笔记已更新')
    } catch (e) { toast.apiError(e, '更新失败') }
    finally { editSaving.value = false }
  }

  async function handleDeleteNote(id: string) {
    try {
      await api.delete(`/notes/${id}`)
      notes.value = notes.value.filter((n: NoteItem) => n.id !== id)
    } catch (e) { toast.apiError(e, '删除笔记失败，请重试') }
  }

  return { noteContent, noteSaving, handleAddNote, handleDeleteNote, showEditModal, editingContent, editIsPrivate, editSaving, handleOpenEdit, handleSaveEdit }
}
