'use client'
import {createContext, ReactNode, useContext, useEffect, useMemo, useRef, useState} from 'react'
import {StoreApi} from 'zustand/vanilla'
import {useStore} from 'zustand/react'
import {createProfileStore, ProfileStore} from '@/lib/stores/profile'
import {createLayoutStore, LayoutStore} from '@/lib/stores/layout'
import {ClientStore, createClientStore} from '@/lib/stores/client'

const StoreContext = createContext<{
  profile?: StoreApi<ProfileStore>
  layout?: StoreApi<LayoutStore>
  client?: StoreApi<ClientStore>
}>({})

export function useProfileStore<T>(selector: (store: ProfileStore) => T) {
  const profile = useContext(StoreContext).profile
  if (!profile) {
    throw new Error('useProfileStore must be used within a StoreProvider')
  }
  return useStore(profile, selector)
}

export function useLayoutStore<T>(selector: (store: LayoutStore) => T) {
  const layout = useContext(StoreContext).layout
  if (!layout) {
    throw new Error('useLayoutStore must be used within a StoreProvider')
  }
  return useStore(layout, selector)
}

export function useClientStore<T>(selector: (store: ClientStore) => T) {
  const client = useContext(StoreContext).client
  if (!client) {
    throw new Error('useClientStore must be used within a StoreProvider')
  }
  return useStore(client, selector)
}

export type ProfileProviderProps = {
  children: ReactNode
}

export default function StoresProvider(props: ProfileProviderProps) {
  console.log('init stores')

  const [profile] = useState(createProfileStore())
  const [layout] = useState(createLayoutStore())
  const [client] = useState(createClientStore())

  const refreshProfile = useStore(profile, store => store.refreshProfile)
  useEffect(() => {
    refreshProfile()
  }, [refreshProfile])

  return (
    <StoreContext.Provider value={{
      profile,
      layout,
      client,
    }}>
      {props.children}
    </StoreContext.Provider>
  )
}
