import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Document, Tag } from '@/types'
import { useApi } from '@/composables/useApi'

export const useDocumentsStore = defineStore('documents', () => {
  const currentDocument = ref<Document | null>(null)
  const tags = ref<Tag[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)
  const saving = ref(false)

  const api = useApi()

  async function fetchDocument(id: string) {
    loading.value = true
    error.value = null
    try {
      currentDocument.value = await api.get<Document>(`/documents/${id}`)
    } catch (e) {
      error.value = e instanceof Error ? e.message : 'Failed to fetch document'
      throw e
    } finally {
      loading.value = false
    }
  }

  async function createDocument(projectId: string, title: string, content: string = '', folderId: string | null = null) {
    const body: { title: string; content: string; folder_id?: string } = { title, content }
    if (folderId) {
      body.folder_id = folderId
    }
    const doc = await api.post<Document>(`/projects/${projectId}/documents`, body)
    
    // Refresh current project tree if needed
    return doc
  }

  async function updateDocument(id: string, title: string, folderId?: string | null) {
    const body: { title: string; folder_id?: string | null } = { title }
    if (folderId !== undefined) {
      body.folder_id = folderId
    }
    const doc = await api.put<Document>(`/documents/${id}`, body)
    if (currentDocument.value?.id === id) {
      currentDocument.value = doc
    }
    return doc
  }

  async function updateDocumentContent(id: string, content: string) {
    saving.value = true
    try {
      await api.put(`/documents/${id}/content`, { content })
      if (currentDocument.value?.id === id) {
        currentDocument.value.content = content
      }
    } finally {
      saving.value = false
    }
  }

  async function deleteDocument(id: string) {
    await api.delete(`/documents/${id}`)
    if (currentDocument.value?.id === id) {
      currentDocument.value = null
    }
  }

  async function fetchTags() {
    try {
      tags.value = await api.get<Tag[]>('/tags')
    } catch (e) {
      console.error('Failed to fetch tags:', e)
    }
  }

  async function createTag(name: string, color: string) {
    const tag = await api.post<Tag>('/tags', { name, color })
    tags.value.push(tag)
    return tag
  }

  async function assignTags(documentId: string, tagIds: string[]) {
    await api.put(`/documents/${documentId}/tags`, { tag_ids: tagIds })
    if (currentDocument.value?.id === documentId) {
      currentDocument.value.tags = tags.value.filter(t => tagIds.includes(t.id))
    }
  }

  async function removeTag(documentId: string, tagId: string) {
    await api.delete(`/documents/${documentId}/tags/${tagId}`)
    if (currentDocument.value?.id === documentId) {
      currentDocument.value.tags = currentDocument.value.tags.filter(t => t.id !== tagId)
    }
  }

  return {
    currentDocument,
    tags,
    loading,
    error,
    saving,
    fetchDocument,
    createDocument,
    updateDocument,
    updateDocumentContent,
    deleteDocument,
    fetchTags,
    createTag,
    assignTags,
    removeTag
  }
})
