'use client'

import { useCallback } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { useAuthReady } from '@/lib/api/use-auth-ready'
import {
  useCreateLabel,
  useUpdateLabel,
  useDeleteLabel,
  useReorderLabels,
} from '@/lib/api/hooks/use-folder-label-queries'
import {
  useCreateUnifiedFolder,
  useUpdateUnifiedFolder,
  useDeleteUnifiedFolder,
  useReorderUnifiedFolders,
} from '@/lib/api/hooks/use-unified-folder-queries'
import type {
  LabelReorderItem,
  UnifiedFolderReorderItem,
} from '@/lib/nav-reorder-plan'

export function useSidebarNavApiSync() {
  const { ready, authenticated } = useAuthReady()
  const queryClient = useQueryClient()
  const apiEnabled = ready && authenticated

  const invalidateNav = useCallback(() => {
    void queryClient.invalidateQueries({ queryKey: ['labels'] })
    void queryClient.invalidateQueries({ queryKey: ['unified-folders'] })
  }, [queryClient])

  const createLabel = useCreateLabel()
  const updateLabel = useUpdateLabel()
  const deleteLabel = useDeleteLabel()
  const reorderLabels = useReorderLabels()
  const createFolder = useCreateUnifiedFolder()
  const updateFolder = useUpdateUnifiedFolder()
  const deleteFolder = useDeleteUnifiedFolder()
  const reorderFolders = useReorderUnifiedFolders()

  return {
    apiEnabled,
    invalidateNav,
    createLabel: (payload: { name: string; color: string }) => {
      if (!apiEnabled) return false
      createLabel.mutate(payload, { onSuccess: invalidateNav })
      return true
    },
    updateLabel: (payload: { id: string; name?: string; color?: string }) => {
      if (!apiEnabled) return false
      updateLabel.mutate(payload, { onSuccess: invalidateNav })
      return true
    },
    deleteLabel: (id: string) => {
      if (!apiEnabled) return false
      deleteLabel.mutate(id, { onSuccess: invalidateNav })
      return true
    },
    reorderLabels: (items: LabelReorderItem[]) => {
      if (!apiEnabled || items.length === 0) return false
      reorderLabels.mutate(items, { onSuccess: invalidateNav })
      return true
    },
    createFolder: (payload: {
      name: string
      color?: string
      account_id?: string
      parent_id?: string
    }) => {
      if (!apiEnabled) return false
      createFolder.mutate(payload, { onSuccess: invalidateNav })
      return true
    },
    updateFolder: (payload: {
      id: string
      name: string
      color: string
      sort_order?: number
      parent_id?: string | null
    }) => {
      if (!apiEnabled) return false
      updateFolder.mutate(payload, { onSuccess: invalidateNav })
      return true
    },
    deleteFolder: (id: string) => {
      if (!apiEnabled) return false
      deleteFolder.mutate(id, { onSuccess: invalidateNav })
      return true
    },
    reorderFolders: (items: UnifiedFolderReorderItem[]) => {
      if (!apiEnabled || items.length === 0) return false
      reorderFolders.mutate(items, { onSuccess: invalidateNav })
      return true
    },
  }
}
