import { ref } from 'vue'
import * as select from '@zag-js/select'

type SelectOption = { label: string; value: string }

export const GUARD_OPTIONS: SelectOption[] = [
  { label: 'api', value: 'api' },
  { label: 'web', value: 'web' },
]

export const CONTEXT_OPTIONS: SelectOption[] = [
  { label: 'member', value: 'member' },
  { label: 'admin', value: 'admin' },
]

function createSelectCollection(options: SelectOption[]) {
  return select.collection({
    items: options,
    itemToValue: (item) => item.label,
  })
}

export function useRoleSelectFields(
  initialGuard: 'api' | 'web' = 'api',
  initialContext: 'member' | 'admin' = 'member',
) {
  const guardCollection = createSelectCollection(GUARD_OPTIONS)
  const contextCollection = createSelectCollection(CONTEXT_OPTIONS)

  const guardValue = ref<string[]>([initialGuard])
  const contextValue = ref<string[]>([initialContext])
  const guardInitial = ref<string[]>([initialGuard])
  const contextInitial = ref<string[]>([initialContext])

  function setGuardValue(details: { value: string[] }) {
    guardValue.value = details.value
  }

  function setContextValue(details: { value: string[] }) {
    contextValue.value = details.value
  }

  function syncFromRole(guard: string, roleContext: string) {
    const guardName = guard === 'web' ? 'web' : 'api'
    const contextName = roleContext === 'admin' ? 'admin' : 'member'
    guardValue.value = [guardName]
    contextValue.value = [contextName]
    guardInitial.value = [guardName]
    contextInitial.value = [contextName]
  }

  function getGuardName(): 'api' | 'web' {
    return guardValue.value[0] === 'web' ? 'web' : 'api'
  }

  function getContext(): 'member' | 'admin' {
    return contextValue.value[0] === 'admin' ? 'admin' : 'member'
  }

  return {
    guardCollection,
    contextCollection,
    guardValue,
    contextValue,
    guardInitial,
    contextInitial,
    setGuardValue,
    setContextValue,
    syncFromRole,
    getGuardName,
    getContext,
  }
}
