/* eslint-disable react-compiler/react-compiler -- the transport branch in `useNavigateToStudioDocument` is a deliberate rules-of-hooks exception; the compiler refuses files that disable it */
import {type Bridge, SDK_CHANNEL_NAME, SDK_NODE_NAME} from '@sanity/message-protocol'
import {type DocumentHandle} from '@sanity/sdk'
import {isMessageBusEnvironment} from '@sanity/sdk/_internal'
import {useCallback} from 'react'

import {urlFor} from '../../dashboard/urlFor'
import {useWindowConnection} from '../comlink/useWindowConnection'
import {useEmit} from './useEmit'
import {
  type DashboardResource,
  useStudioWorkspacesByProjectIdDataset,
} from './useStudioWorkspacesByProjectIdDataset'

/**
 * @public
 * @category Types
 * @category Documents
 */
export interface NavigateToStudioResult {
  navigateToStudioDocument: () => void
}

function useComlinkStudioNavigator(
  documentHandle: DocumentHandle,
): (workspace: DashboardResource) => void {
  const {sendMessage} = useWindowConnection<Bridge.Navigation.NavigateToResourceMessage, never>({
    name: SDK_NODE_NAME,
    connectTo: SDK_CHANNEL_NAME,
  })

  return useCallback(
    (workspace: DashboardResource) => {
      const message: Bridge.Navigation.NavigateToResourceMessage = {
        type: 'dashboard/v1/bridge/navigate-to-resource',
        data: {
          resourceId: workspace.id,
          resourceType: 'studio',
          path: `/intent/edit/id=${documentHandle.documentId};type=${documentHandle.documentType}`,
        },
      }
      sendMessage(message.type, message.data)
    },
    [documentHandle, sendMessage],
  )
}

function useBusStudioNavigator(
  documentHandle: DocumentHandle,
): (workspace: DashboardResource) => void {
  const navigate = useEmit('navigation.location.update')

  return useCallback(
    (workspace: DashboardResource) => {
      const url = urlFor
        .studios(workspace.userApplicationId)
        .workspace(workspace.name)
        .intent('edit', {id: documentHandle.documentId, type: documentHandle.documentType})
        .url()
      navigate({url}).then(
        (reply) => {
          if (reply.ok === false) {
            // eslint-disable-next-line no-console
            console.warn('Failed to navigate to studio document', reply)
          }
        },
        // The reply can reject (no responder, timeout, aborted); navigation is best-effort, so
        // warn instead of throwing.
        (error) => {
          // eslint-disable-next-line no-console
          console.warn('Failed to navigate to studio document', error)
        },
      )
    },
    [documentHandle, navigate],
  )
}

/**
 * @public
 *
 * Hook that provides a function to navigate to a given document in its parent Studio.
 *
 * Uses the `projectId` and `dataset` properties of the {@link DocumentHandle} you provide to resolve the correct Studio.
 * This will only work if you have deployed a studio with a workspace with this `projectId` / `dataset` combination.
 *
 * Works in both Dashboard runtimes: it sends the navigation over the Comlink connection in the
 * iframe runtime and over the message bus in the federated runtime.
 *
 * @remarks If you write your own Document Handle to pass to this hook (as opposed to a Document Handle generated by another hook),
 * it must include values for `documentId`, `documentType`, `projectId`, and `dataset`.
 *
 * @category Documents
 * @param documentHandle - The document handle for the document to navigate to
 * @param preferredStudioUrl - The preferred studio url to navigate to if you have multiple
 * studios with the same projectId and dataset
 * @returns An object containing:
 * - `navigateToStudioDocument` - Function that when called will navigate to the studio document
 *
 * @example
 * ```tsx
 * import {type DocumentHandle} from '@sanity/sdk-react'
 * import {useNavigateToStudioDocument} from '@sanity/sdk-react/dashboard'
 * import {Button} from '@sanity/ui'
 * import {Suspense} from 'react'
 *
 * function NavigateButton({documentHandle}: {documentHandle: DocumentHandle}) {
 *   const {navigateToStudioDocument} = useNavigateToStudioDocument(documentHandle)
 *   return (
 *     <Button
 *       onClick={navigateToStudioDocument}
 *       text="Navigate to Studio Document"
 *     />
 *   )
 * }
 *
 * // Wrap the component with Suspense since the hook may suspend
 * function MyDocumentAction({documentHandle}: {documentHandle: DocumentHandle}) {
 *   return (
 *     <Suspense fallback={<Button text="Loading..." disabled />}>
 *       <NavigateButton documentHandle={documentHandle} />
 *     </Suspense>
 *   )
 * }
 * ```
 */
export function useNavigateToStudioDocument(
  documentHandle: DocumentHandle,
  preferredStudioUrl?: string,
): NavigateToStudioResult {
  const {workspacesByProjectIdAndDataset} = useStudioWorkspacesByProjectIdDataset()
  // The branch is stable: the transport is fixed for the page lifetime, so one navigator hook
  // always runs and the other never does.
  const sendToWorkspace = isMessageBusEnvironment()
    ? // eslint-disable-next-line react-hooks/rules-of-hooks -- transport is fixed for the page lifetime
      useBusStudioNavigator(documentHandle)
    : // eslint-disable-next-line react-hooks/rules-of-hooks -- transport is fixed for the page lifetime
      useComlinkStudioNavigator(documentHandle)

  const navigateToStudioDocument = useCallback(() => {
    const {projectId, dataset} = documentHandle

    if (!projectId || !dataset) {
      // eslint-disable-next-line no-console
      console.warn('Project ID and dataset are required to navigate to a studio document')
      return
    }

    const workspace = resolveWorkspace(
      documentHandle,
      workspacesByProjectIdAndDataset,
      preferredStudioUrl,
    )

    if (!workspace) {
      // eslint-disable-next-line no-console
      console.warn(
        `No workspace found for document with projectId: ${projectId} and dataset: ${dataset}${preferredStudioUrl ? ` or with preferred studio url: ${preferredStudioUrl}` : ''}`,
      )
      return
    }

    sendToWorkspace(workspace)
  }, [documentHandle, workspacesByProjectIdAndDataset, preferredStudioUrl, sendToWorkspace])

  return {
    navigateToStudioDocument,
  }
}

type WorkspacesByProjectIdDataset = ReturnType<
  typeof useStudioWorkspacesByProjectIdDataset
>['workspacesByProjectIdAndDataset']

function resolveWorkspace(
  documentHandle: DocumentHandle,
  workspacesByProjectIdAndDataset: WorkspacesByProjectIdDataset,
  preferredStudioUrl?: string,
): DashboardResource | undefined {
  const {projectId, dataset} = documentHandle
  const key = `${projectId}:${dataset}` as const

  if (preferredStudioUrl) {
    // Include workspaces without projectId/dataset in case their manifest has not loaded yet.
    const allWorkspaces = [
      ...(workspacesByProjectIdAndDataset[key] || []),
      ...(workspacesByProjectIdAndDataset['NO_PROJECT_ID:NO_DATASET'] || []),
    ]
    return allWorkspaces.find((w) => w.url === preferredStudioUrl)
  }

  const workspaces = workspacesByProjectIdAndDataset[key]
  if (workspaces && workspaces.length > 1) {
    // eslint-disable-next-line no-console
    console.warn(
      'Multiple workspaces found for document and no preferred studio url',
      documentHandle,
    )
    // eslint-disable-next-line no-console
    console.warn('Using the first one', workspaces[0])
  }
  return workspaces?.[0]
}
