import { ref, onMounted } from 'vue'
import { api } from '../api/client'
import { useToast } from './useToast'

interface Highlight {
  id: string
  type: string
  page: number
  position: Record<string, unknown>
  text: string | null
  note: string | null
  color: string
  created_at: string | null
}

export function useHighlights(pmid: number) {
  const toast = useToast()

  const highlights = ref<Highlight[]>([])
  const hlsLoading = ref(false)
  const showHlForm = ref(false)
  const hlText = ref('')
  const hlNote = ref('')
  const hlType = ref<'highlight' | 'underline' | 'strikethrough' | 'free_text'>('highlight')
  const hlColor = ref('#ffff00')
  const hlToolbarVisible = ref(false)
  const hlToolbarPos = ref({ x: 0, y: 0 })

  async function loadHighlights() {
    hlsLoading.value = true
    try {
      const { data } = await api.get(`/highlights/${pmid}`)
      highlights.value = data || []
    } catch { highlights.value = [] }
    finally { hlsLoading.value = false }
  }

  async function handleCreateHighlight() {
    if (!hlText.value.trim()) return
    try {
      await api.post(`/highlights/${pmid}`, {
        highlight_type: hlType.value,
        page_number: 0,
        position: {},
        text: hlText.value.trim(),
        note: hlNote.value.trim() || null,
        color: hlColor.value,
      })
      hlText.value = ''
      hlNote.value = ''
      showHlForm.value = false
      await loadHighlights()
    } catch (e) { toast.apiError(e, '保存标注失败') }
  }

  async function handleDeleteHighlight(hid: string) {
    try {
      await api.delete(`/highlights/${hid}`)
      highlights.value = highlights.value.filter((h: Highlight) => h.id !== hid)
    } catch (e) { toast.apiError(e, '删除标注失败') }
  }

  function onAbstractMouseup(e: MouseEvent) {
    const sel = window.getSelection()
    if (!sel || sel.isCollapsed || !sel.toString().trim()) {
      hlToolbarVisible.value = false
      return
    }
    hlToolbarPos.value = { x: e.clientX, y: e.clientY }
    hlToolbarVisible.value = true
  }

  function useSelectedText() {
    const sel = window.getSelection()
    if (sel && !sel.isCollapsed) {
      hlText.value = sel.toString().trim()
      sel.removeAllRanges()
    }
    hlToolbarVisible.value = false
    showHlForm.value = true
  }

  onMounted(() => { loadHighlights() })

  return {
    highlights, hlsLoading, showHlForm,
    hlText, hlNote, hlType, hlColor,
    hlToolbarVisible, hlToolbarPos,
    handleCreateHighlight, handleDeleteHighlight,
    onAbstractMouseup, useSelectedText,
  }
}
