import {
  type GetUsersOptions,
  getUsersState,
  loadMoreUsers,
  resolveUsers,
  type SanityUser,
} from '@sanity/sdk'
import {getUsersKey, parseUsersKey} from '@sanity/sdk/_internal'
import {useCallback, useEffect, useMemo, useState, useSyncExternalStore, useTransition} from 'react'

import {useSanityInstance} from '../context/useSanityInstance'
import {useResolvedProjectId} from '../helpers/useResolvedProjectId'
import {trackHookUsage} from '../helpers/useTrackHookUsage'

/**
 * @public
 * @category Types
 * @category Users
 */
export interface UsersResult {
  /**
   * The users fetched.
   */
  data: SanityUser[]
  /**
   * How many users the resource has, including those not fetched yet.
   */
  totalCount: number
  /**
   * Whether there are more users to fetch.
   */
  hasMore: boolean

  /**
   * Whether a users request is currently in progress
   */
  isPending: boolean
  /**
   * Load more users.
   */
  loadMore: () => void
}

/**
 * Injects a resolved `projectId` into project-scoped users options. A missing
 * `projectId` is a no-op, and organization-scoped queries (explicit
 * `resourceType`/`organizationId`) or options that already carry a `projectId`
 * are returned unchanged.
 */
function withResolvedProjectId(
  options: GetUsersOptions | undefined,
  projectId: string | undefined,
): GetUsersOptions | undefined {
  if (!projectId) return options
  if (!options) return {projectId}
  const isOrgScoped = options.resourceType === 'organization' || !!options.organizationId
  if (isOrgScoped || options.projectId) return options
  return {...options, projectId}
}

/**
 *
 * @public
 *
 * Retrieves the users for a given resource (either a project or an organization).
 *
 * @category Users
 * @param params - The resource type, project ID, and the limit of users to fetch
 * @returns A list of users, how many users the resource has in total, a boolean indicating whether there are more users to fetch, and a function to load more users
 *
 * @example
 * ```
 * const { data, totalCount, hasMore, loadMore, isPending } = useUsers({
 *   resourceType: 'organization',
 *   organizationId: 'my-org-id',
 *   batchSize: 10,
 * })
 *
 * return (
 *   <div>
 *     {data.map(user => (
 *       <figure key={user.sanityUserId}>
 *         <img src={user.profile.imageUrl} alt='' />
 *         <figcaption>{user.profile.displayName}</figcaption>
 *         <address>{user.profile.email}</address>
 *       </figure>
 *     ))}
 *     <p>Showing {data.length} of {totalCount}</p>
 *     {hasMore && <button onClick={loadMore}>{isPending ? 'Loading...' : 'Load More'}</button>}
 *   </div>
 * )
 * ```
 * @remarks
 * For project-scoped queries the `projectId` is resolved in order from:
 * 1. an explicit `projectId` option
 * 2. A legacy ProjectContext (e.g. a `<ResourceProvider projectId="…">` with no dataset), then
 * 3. The active resource (`ResourceProvider`/`SDKProvider`)
 * 4. `instance.config`.
 */
export function useUsers(options?: GetUsersOptions): UsersResult {
  const instance = useSanityInstance()
  trackHookUsage(instance, 'useUsers')
  // Use React's useTransition to avoid UI jank when user options change
  const [isPending, startTransition] = useTransition()

  // Resolve the projectId from the ambient project/resource context so a
  // project-scoped users request can pick it up rather than the top-level config.
  const resolvedProjectId = useResolvedProjectId(options)
  const effectiveOptions = useMemo(
    () => withResolvedProjectId(options, resolvedProjectId),
    [options, resolvedProjectId],
  )

  // Get the unique key for this users request and its options
  const key = getUsersKey(instance, effectiveOptions)
  // Use a deferred state to avoid immediate re-renders when the users request changes
  const [deferredKey, setDeferredKey] = useState(key)
  // Parse the deferred users key back into users options
  const deferred = useMemo(() => parseUsersKey(deferredKey), [deferredKey])

  // Create an AbortController to cancel in-flight requests when needed
  const [ref, setRef] = useState<AbortController>(new AbortController())

  // When the users request or options change, start a transition to update the request
  useEffect(() => {
    if (key === deferredKey) return

    startTransition(() => {
      if (!ref.signal.aborted) {
        ref.abort()
        setRef(new AbortController())
      }

      setDeferredKey(key)
    })
  }, [deferredKey, key, ref])

  // Get the state source for this users request from the users store
  const {getCurrent, subscribe} = useMemo(() => {
    return getUsersState(instance, deferred)
  }, [instance, deferred])

  // If data isn't available yet, suspend rendering until it is
  // This is the React Suspense integration - throwing a promise
  // will cause React to show the nearest Suspense fallback
  if (getCurrent() === undefined) {
    throw resolveUsers(instance, {...deferred, signal: ref.signal})
  }

  // Subscribe to updates and get the current data
  // useSyncExternalStore ensures the component re-renders when the data changes
  const {data, totalCount, hasMore} = useSyncExternalStore(subscribe, getCurrent)!

  const loadMore = useCallback(() => {
    loadMoreUsers(instance, effectiveOptions)
  }, [instance, effectiveOptions])

  return {data, totalCount, hasMore, isPending, loadMore}
}
