import { computed, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import * as combobox from '@zag-js/combobox'
import Swal from 'sweetalert2'
import { useAuthStore } from '@/stores/auth'
import { resolvePostLoginRoute } from '@/modules/auth'

export function useRoleSwitcher() {
  const authStore = useAuthStore()
  const router = useRouter()

  const switchingRole = ref(false)
  const selectedRoleId = ref('')
  const roleComboValue = ref<string[]>([''])

  const roleOptions = ref<{ value: string; label: string }[]>([])

  const availableRoles = computed(() => authStore.roles ?? [])
  const canSwitchRole = computed(() => availableRoles.value.length > 1)

  function syncRoleSwitcherFromSession() {
    const roles = availableRoles.value
    roleOptions.value = roles.map((r) => ({
      value: r.id,
      label: r.name,
    }))

    const activeId = authStore.activeRole?.id ?? ''
    selectedRoleId.value = activeId
    roleComboValue.value = activeId ? [activeId] : ['']
  }

  watch(
    () => [authStore.user?.id, authStore.activeRole?.id, authStore.roles?.length] as const,
    () => syncRoleSwitcherFromSession(),
    { immediate: true },
  )

  const roleCollection = computed(() =>
    combobox.collection({
      items: roleOptions.value,
      itemToValue: (item) => item.value,
      itemToString: (item) => item.label,
    }),
  )

  const onRoleValueChange = async (details: { value: string[] }) => {
    const nextRoleId = details.value?.[0] ?? ''

    if (!nextRoleId) {
      roleComboValue.value = authStore.activeRole?.id ? [authStore.activeRole.id] : ['']
      selectedRoleId.value = authStore.activeRole?.id ?? ''
      return
    }

    if (nextRoleId === authStore.activeRole?.id || switchingRole.value || authStore.loading) {
      roleComboValue.value = [nextRoleId]
      selectedRoleId.value = nextRoleId
      return
    }

    roleComboValue.value = [nextRoleId]
    selectedRoleId.value = nextRoleId
    await onSwitchRole(nextRoleId)
  }

  const onRoleInputValueChange = ({ inputValue }: { inputValue: string }) => {
    const query = (inputValue ?? '').toLowerCase()
    const all = availableRoles.value.map((r) => ({
      value: r.id,
      label: r.name,
    }))

    const filtered = all.filter((item) => item.label.toLowerCase().includes(query))
    roleOptions.value = filtered.length > 0 ? filtered : all
  }

  const onSwitchRole = async (roleId: string) => {
    if (!roleId || roleId === authStore.activeRole?.id) return

    switchingRole.value = true
    try {
      const res = await authStore.switchRole(roleId)

      await Swal.fire({
        toast: true,
        position: 'top-end',
        icon: 'success',
        title: res.message || 'Peranan telah ditukar.',
        showConfirmButton: false,
        timer: 3000,
      })

      await router.push(resolvePostLoginRoute(res.redirect_path))
    } finally {
      switchingRole.value = false
    }
  }

  return {
    canSwitchRole,
    roleCollection,
    roleComboValue,
    switchingRole,
    onRoleValueChange,
    onRoleInputValueChange,
  }
}
