import { useCallback, useEffect, useState } from 'react'
import { api, type Tag, type TagColor } from '../api/client'

// useTags owns the user's tag roster (the full set the writer has created, with
// per-tag document counts). Document↔tag assignments live in App alongside the
// document list; this hook is just the roster plus create/recolor/delete and a
// refresh used to keep counts current after an assignment changes.
export function useTags() {
  const [tags, setTags] = useState<Tag[]>([])

  const refresh = useCallback(async () => {
    try {
      setTags(await api.listTags())
    } catch (err) {
      console.error('failed to load tags', err)
    }
  }, [])

  useEffect(() => {
    void refresh()
  }, [refresh])

  // Create (or reuse) a tag, returning it. The roster is refreshed so the new
  // tag appears with a zero count.
  const createTag = useCallback(
    async (name: string, color: TagColor): Promise<Tag | null> => {
      try {
        const tag = await api.createTag(name, color)
        await refresh()
        return tag
      } catch (err) {
        console.error('failed to create tag', err)
        return null
      }
    },
    [refresh],
  )

  const recolorTag = useCallback(
    async (id: string, color: TagColor) => {
      // Optimistic recolor; refresh reconciles.
      setTags((prev) => prev.map((t) => (t.id === id ? { ...t, color } : t)))
      try {
        await api.updateTag(id, { color })
      } catch (err) {
        console.error('failed to recolor tag', err)
        void refresh()
      }
    },
    [refresh],
  )

  const deleteTag = useCallback(async (id: string) => {
    setTags((prev) => prev.filter((t) => t.id !== id))
    try {
      await api.deleteTag(id)
    } catch (err) {
      console.error('failed to delete tag', err)
    }
  }, [])

  return { tags, refresh, createTag, recolorTag, deleteTag }
}
