import { useMemo, useEffect } from 'react'
import { createBridge } from '@/services/webviewBridge'
import { configureBridgeAdapters } from '@/services/webviewBridge/adapters'
import { useFilePicker } from '@/hooks/useFilePicker'
import { useAuthStore } from '@/stores/auth'

/**
 * 创建桥接并配置端侧适配器，推送 token 变更事件。
 * @param {import('react').MutableRefObject} webRef WebView ref
 */
export const useBridge = (webRef) => {
  const bridge = useMemo(() => createBridge(webRef), [webRef])
  const { openAlbum, openSystemCamera, openDocument } = useFilePicker()

  useEffect(() => {
    configureBridgeAdapters({
      media: { openAlbum },
      camera: { openSystemCamera },
      file: { openDocument },
      router: {
        async goBack() {
          if (webRef.current) {
            try {
              const canGoBack = webRef.current.canGoBack || false
              if (canGoBack) {
                webRef.current.goBack()
                return
              }
            } catch (_) {}
          }
          try {
            const { router } = require('expo-router')
            router.back()
          } catch (_) {}
        },
        async backTo({ path, params } = {}) {
          try {
            const { router } = require('expo-router')
            if (!path || typeof path !== 'string') throw new Error('path required')
            router.replace({ pathname: path, params: params || {} })
          } catch (_) {}
        },
        async push(payload) {
          try {
            const { router } = require('expo-router')
            let path = null; let params = undefined; let options = undefined
            if (typeof payload === 'string') {
              path = payload
            } else if (payload && typeof payload === 'object') {
              path = payload.path || payload.pathname
              params = payload.params
              options = payload.options
            }
            if (!path || typeof path !== 'string') throw new Error('path required')
            const mergedParams = {
              ...(options && typeof options === 'object' ? options : {}),
              ...(params && typeof params === 'object' ? params : {}),
            }
            router.push({ pathname: path, params: mergedParams })
          } catch (_) {}
        },
        async replace(payload) {
          try {
            const { router } = require('expo-router')
            let path = null; let params = undefined; let options = undefined
            if (typeof payload === 'string') {
              path = payload
            } else if (payload && typeof payload === 'object') {
              path = payload.path || payload.pathname
              params = payload.params
              options = payload.options
            }
            if (!path || typeof path !== 'string') throw new Error('path required')
            const mergedParams = {
              ...(options && typeof options === 'object' ? options : {}),
              ...(params && typeof params === 'object' ? params : {}),
            }
            router.replace({ pathname: path, params: mergedParams })
          } catch (_) {}
        },
      },
    })
  }, [openAlbum, openSystemCamera, openDocument, webRef])

  useEffect(() => {
    const unsubscribe = useAuthStore.subscribe(
      (state) => state.token,
      (token, prev) => {
        if (token === prev) return
        try { bridge.emit('auth.tokenUpdated', { token }) } catch (_) {}
      }
    )
    return () => { try { unsubscribe && unsubscribe() } catch (_) {} }
  }, [bridge])

  return bridge
}