import {type ActionsResult, type DocumentAction, type ResolveDocument} from '@sanity/sdk'

import {type ResourceHandle} from '../../config/handles'
import {useApplyActions} from '../helpers/useApplyActions'
// this import is used in an `{@link useEditDocument}`
// eslint-disable-next-line import-x/consistent-type-specifier-style
import type {useEditDocument} from './useEditDocument'

/**
 * @public
 */
interface UseApplyDocumentActions {
  (): <
    TDocumentType extends string = string,
    TDataset extends string = string,
    TProjectId extends string = string,
  >(
    action:
      | DocumentAction<TDocumentType, TDataset, TProjectId>
      | DocumentAction<TDocumentType, TDataset, TProjectId>[],
    options?: ResourceHandle,
  ) => Promise<ActionsResult<ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`>>>
}

/**
 * @public
 *
 * Provides a stable callback function for applying one or more document actions.
 *
 * This hook wraps the core `applyDocumentActions` functionality from `@sanity/sdk`,
 * integrating it with the React component lifecycle and {@link SanityInstance}.
 * It allows you to apply actions generated by functions like `createDocument`,
 * `editDocument`, `deleteDocument`, `publishDocument`, `unpublishDocument`,
 * and `discardDocument` to documents.
 *
 * Features:
 * - Applies one or multiple `DocumentAction` objects.
 * - Supports optimistic updates: Local state reflects changes immediately.
 * - Handles batching: Multiple actions passed together are sent as a single atomic transaction.
 * - Integrates with the collaborative editing engine for conflict resolution and state synchronization.
 *
 * @category Documents
 * @returns A stable callback function. When called with a single `DocumentAction` or an array of `DocumentAction`s,
 * it returns a promise that resolves to an {@link ActionsResult}. The `ActionsResult` contains information about the
 * outcome, including optimistic results if applicable.
 *
 * @remarks
 * This hook is a fundamental part of interacting with document state programmatically.
 * It operates within the same unified pipeline as other document hooks like `useDocument` (for reading state)
 * and {@link useEditDocument} (a higher-level hook specifically for edits).
 *
 * When multiple actions are provided in a single call, they are guaranteed to be submitted
 * as a single transaction to Content Lake. This ensures atomicity for related operations (e.g., creating and publishing a document).
 *
 * @function
 *
 * @example Publish or unpublish a document
 * ```tsx
 * import {
 *   publishDocument,
 *   unpublishDocument,
 *   useApplyDocumentActions,
 *   type DocumentHandle
 * } from '@sanity/sdk-react'
 *
 * // Define props using the DocumentHandle type
 * interface PublishControlsProps {
 *   doc: DocumentHandle
 * }
 *
 * function PublishControls({doc}: PublishControlsProps) {
 *   const apply = useApplyDocumentActions()
 *
 *   const handlePublish = () =>  apply(publishDocument(doc))
 *   const handleUnpublish = () => apply(unpublishDocument(doc))
 *
 *   return (
 *     <>
 *       <button onClick={handlePublish}>Publish</button>
 *       <button onClick={handleUnpublish}>Unpublish</button>
 *     </>
 *   )
 * }
 * ```
 *
 * @example Create and publish a new document
 * ```tsx
 * import {
 *   createDocument,
 *   publishDocument,
 *   createDocumentHandle,
 *   useApplyDocumentActions
 * } from '@sanity/sdk-react'
 *
 * function CreateAndPublishButton({documentType}: {documentType: string}) {
 *   const apply = useApplyDocumentActions()
 *
 *   const handleCreateAndPublish = () => {
 *     // Create a new handle inside the handler
 *     const newDocHandle = createDocumentHandle({ documentId: crypto.randomUUID(), documentType })
 *
 *     // Apply multiple actions for the new handle as a single transaction
 *     apply([
 *       createDocument(newDocHandle),
 *       publishDocument(newDocHandle),
 *     ])
 *   }
 *
 *   return (
 *     <button onClick={handleCreateAndPublish}>
 *       I'm feeling lucky
 *     </button>
 *   )
 * }
 * ```
 *
 * @example Create a document with initial field values
 * ```tsx
 * import {
 *   createDocument,
 *   createDocumentHandle,
 *   useApplyDocumentActions
 * } from '@sanity/sdk-react'
 *
 * function CreateArticleButton() {
 *   const apply = useApplyDocumentActions()
 *
 *   const handleCreateArticle = () => {
 *     const newDocHandle = createDocumentHandle({
 *       documentId: crypto.randomUUID(),
 *       documentType: 'article'
 *     })
 *
 *     // Create document with initial values in one action
 *     apply(
 *       createDocument(newDocHandle, {
 *         title: 'New Article',
 *         author: 'John Doe',
 *         publishedAt: new Date().toISOString(),
 *       })
 *     )
 *   }
 *
 *   return <button onClick={handleCreateArticle}>Create Article</button>
 * }
 * ```
 *
 * @example Create a new document in a release
 * ```tsx
 * import {
 *   createDocument,
 *   createDocumentHandle,
 *   useApplyDocumentActions
 * } from '@sanity/sdk-react'
 *
 * function CreateArticleButton() {
 *   const apply = useApplyDocumentActions()
 *
 *   const handleCreateArticle = () => {
 *     // Use any valid document ID — not the internal `versions.<releaseName>.<id>` format or "drafts.<id>" format.
 *     // New documents must be explicitly created with `createDocument` to become part of a release.
 *     const newDocHandle = createDocumentHandle({
 *       documentId: crypto.randomUUID(), // or the existing document ID you want to make a release version of
 *       documentType: 'article',
 *       perspective: {releaseName: 'summer-drop'},
 *     })
 *
 *     apply(
 *       createDocument(newDocHandle, {
 *         title: 'New Article',
 *         author: 'John Doe',
 *         publishedAt: new Date().toISOString(),
 *       })
 *     )
 *   }
 *
 *   return <button onClick={handleCreateArticle}>Create Article</button>
 * }
 * ```
 *
 * @example Edit an existing document in a release
 * ```tsx
 * import {
 *   editDocument,
 *   createDocumentHandle,
 *   useApplyDocumentActions
 * } from '@sanity/sdk-react'
 *
 * function EditArticleInReleaseButton({documentId}: {documentId: string}) {
 *   const apply = useApplyDocumentActions()
 *
 *   const handleEdit = () => {
 *     // Pass the document's regular ID — not `versions.<releaseName>.<id>`.
 *     // Documents that already have a version in the release can be edited directly with `editDocument`.
 *     const docHandle = createDocumentHandle({
 *       documentId,
 *       documentType: 'article',
 *       perspective: {releaseName: 'summer-drop'},
 *     })
 *
 *     apply(editDocument(docHandle, {set: {title: 'Updated for release'}}))
 *   }
 *
 *   return <button onClick={handleEdit}>Edit in Release</button>
 * }
 * ```
 */
export const useApplyDocumentActions: UseApplyDocumentActions = () => {
  return useApplyActions() as ReturnType<UseApplyDocumentActions>
}
