import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useCallback } from 'react'
import { useLikeMutation } from 'src/hooks/mutations/useLikeMutation'
import { useConfirmDialog } from 'src/hooks/useConfirmDialog'
import { deleteStatus } from 'src/lib/api'
import type { Status } from 'src/lib/api-types'
import { postQueries } from 'src/lib/queries/posts'

// Per-row mutations + helpers for the thread on `/post/[id]`. The composer
// half (text, target, scope, CW, post-mutation, keyboard tracking) was
// removed when the sticky composer was deleted in favour of the modal
// `PostComposer` on `/camera?inReplyToId=...`. Replies are posted by the
// modal's own `useComposer.handlePost`; the optimistic cache update lands
// via `appendReplyToCachedThread` from there. The hook now owns *only*
// what the screen still uses on every row: like and delete.

type Params = {
  statusId: string
}

export function useThreadActions({ statusId: _statusId }: Params) {
  const queryClient = useQueryClient()
  const { confirm, dialog: confirmDialog } = useConfirmDialog()

  type Ctx = { ancestors: Status[]; descendants: Status[] }

  // Like flows through the shared cache mutation — optimistic apply +
  // rollback + reconcile across home / network / bookmarks / selfLikes /
  // byId / every open thread. No row-specific patching needed.
  const { handleLike } = useLikeMutation()

  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      const res = await deleteStatus({ id })
      return res as Status
    },
    onSuccess: (deleted) => {
      // Drop the row from every open thread cache. Walk every `thread`
      // slice so a delete fired from an ancestor view also updates a
      // sibling descendant thread the user has open in another stack.
      const threadPrefix = postQueries.thread('').queryKey.slice(0, -1)
      const all = queryClient.getQueriesData<Ctx | undefined>({
        queryKey: threadPrefix as unknown as readonly unknown[],
      })
      for (const [key, ctx] of all) {
        if (!ctx) continue
        queryClient.setQueryData<Ctx | undefined>(key, {
          ancestors: ctx.ancestors.filter((s) => s.id !== deleted.id),
          descendants: ctx.descendants.filter((s) => s.id !== deleted.id),
        })
      }
    },
  })

  const likeRow = useCallback(
    (row: Status) => {
      handleLike(row.id, !row.favourited, row.account?.id?.toString())
    },
    [handleLike]
  )

  const deleteRow = useCallback(
    async (id: string) => {
      const ok = await confirm({
        title: 'Delete post?',
        message: 'This cannot be undone.',
        confirmLabel: 'Delete',
        destructive: true,
      })
      if (ok) deleteMutation.mutate(id)
    },
    [confirm, deleteMutation]
  )

  return {
    likeRow,
    deleteRow,
    confirmDialog,
  }
}

export type UseThreadActions = ReturnType<typeof useThreadActions>
