import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'
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)
    })()
  }, [])

  const setBind = useCallback(async (p: BindPayload | null) => {
    setBindState(p)
    if (p) await saveBindPayload(p)
    else await clearBindPayload()
  }, [])

  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
}
