import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'
import { Platform } from 'react-native'
import { isExpoEasyTierVpnAvailable, saveAndPrepareTunnel } from '@/lib/easyTierVpn'
import type { BindPayload } from '@/lib/types'
import { clearBindPayload, loadBindPayload, saveBindPayload } from '@/lib/storage'

type Ctx = {
  bind: BindPayload | null
  ready: boolean
  setBind: (p: BindPayload | null) => Promise<void>
  clear: () => Promise<void>
}

const BindContext = createContext<Ctx | null>(null)

export function BindProvider({ children }: { children: React.ReactNode }) {
  const [bind, setBindState] = useState<BindPayload | null>(null)
  const [ready, setReady] = useState(false)

  useEffect(() => {
    void (async () => {
      const p = await loadBindPayload()
      setBindState(p)
      setReady(true)
    })()
  }, [])

  useEffect(() => {
    if (!ready || !bind) return
    if (Platform.OS === 'android' && isExpoEasyTierVpnAvailable()) {
      void saveAndPrepareTunnel(bind.easytier).catch(() => {})
    }
  }, [ready, bind])

  const setBind = useCallback(async (p: BindPayload | null) => {
    setBindState(p)
    if (p) await saveBindPayload(p)
    else await clearBindPayload()
    if (p && Platform.OS === 'android' && isExpoEasyTierVpnAvailable()) {
      try {
        await saveAndPrepareTunnel(p.easytier)
      } catch {
        /* 组网内核未就绪或用户未授权 VPN 时不阻断配对 */
      }
    }
  }, [])

  const clear = useCallback(async () => {
    setBindState(null)
    await clearBindPayload()
  }, [])

  const value = useMemo(
    () => ({ bind, ready, setBind, clear }),
    [bind, ready, setBind, clear],
  )

  return <BindContext.Provider value={value}>{children}</BindContext.Provider>
}

export function useBind(): Ctx {
  const c = useContext(BindContext)
  if (!c) throw new Error('useBind outside BindProvider')
  return c
}
