<script setup lang="ts">
import type { DropdownMenuItem } from '@nuxt/ui'
import type { NavigationItem } from '../../types/i18nLists'
import { isSuperAdmin } from '../utils/auth'
import { useI18nMenus } from '../composables/useI18nMenus'

defineProps<{
  collapsed?: boolean
  showLoginButton?: boolean
}>()

const toast = useToast()
const { t, tm, rt } = useI18n()
const localePath = useLocalePath()

const { user, signOut } = useAuth()
const userIsSuperAdmin = computed(() => isSuperAdmin(user.value))
const colorMode = useColorMode()
const appConfig = useAppConfig()
const colors = ['red', 'orange', 'amber', 'yellow', 'lime', 'green', 'emerald', 'teal', 'cyan', 'sky', 'blue', 'indigo', 'violet', 'purple', 'fuchsia', 'pink', 'rose']
const neutrals = ['slate', 'gray', 'zinc', 'neutral', 'stone']
const solarIconVariants = ['linear', 'bold', 'outline', 'broken', 'bold-duotone', 'line-duotone']
const accountLinks = ref<NavigationItem[][]>([])

function setSolarIconVariant(variant: SolarIconVariant) {
  (appConfig.saas.ui as { solarIconVariant: SolarIconVariant }).solarIconVariant = variant
}

async function fetchLinks() {
  accountLinks.value = useI18nMenus<NavigationItem>('account.menuItems', tm, rt).map(group =>
    group.map(link => ({
      ...link,
      exact: link.exact?.toString() === 'true'
    }))
  )
}
fetchLinks()
watchEffect(() => {
  fetchLinks()
})

const fallbackAvatarSrc = computed(() => {
  const actualImage = user.value?.image
  if (actualImage && actualImage.length > 0) return actualImage
  const seed = user.value?.name || 'User'
  return `https://ui-avatars.com/api/?name=${encodeURIComponent(seed)}&background=E5E7EB&color=111827&size=64`
})

const items = computed<DropdownMenuItem[][]>(() => ([
  ...accountLinks.value,
  [
    {
      label: 'Theme',
      icon: useSolarIcon('palette'),
      children: [{
        label: 'Primary',
        slot: 'chip',
        chip: appConfig.ui.colors.primary,
        content: {
          align: 'center',
          collisionPadding: 16
        },
        children: colors.map(color => ({
          label: color,
          chip: color,
          slot: 'chip',
          checked: appConfig.ui.colors.primary === color,
          type: 'checkbox',
          onSelect: (e) => {
            e.preventDefault()
            appConfig.ui.colors.primary = color
          }
        }))
      }, {
        label: 'Secondary',
        slot: 'chip',
        chip: appConfig.ui.colors.secondary,
        content: {
          align: 'center',
          collisionPadding: 16
        },
        children: colors.map(color => ({
          label: color,
          chip: color,
          slot: 'chip',
          checked: appConfig.ui.colors.secondary === color,
          type: 'checkbox',
          onSelect: (e) => {
            e.preventDefault()
            appConfig.ui.colors.secondary = color
          }
        }))
      }, {
        label: 'Neutral',
        slot: 'chip',
        chip: appConfig.ui.colors.neutral === 'neutral' ? 'old-neutral' : appConfig.ui.colors.neutral,
        content: {
          align: 'end',
          collisionPadding: 16
        },
        children: neutrals.map(color => ({
          label: color,
          chip: color === 'neutral' ? 'old-neutral' : color,
          slot: 'chip',
          type: 'checkbox',
          checked: appConfig.ui.colors.neutral === color,
          onSelect: (e) => {
            e.preventDefault()
            appConfig.ui.colors.neutral = color
          }
        }))
      }]
    }, {
      label: 'Solar Icons',
      icon: useSolarIcon('pen-new-square'),
      children: (solarIconVariants as SolarIconVariant[]).map(variant => ({
        label: variant,
        icon: useSolarIcon('pen-new-square', variant),
        type: 'checkbox',
        checked: appConfig.saas.ui!.solarIconVariant === variant,
        onSelect: (e) => {
          e.preventDefault()
          setSolarIconVariant(variant)
        }
      }))
    },
    {
      label: 'Appearance',
      icon: useSolarIcon('sun-2'),
      children: [{
        label: 'Light',
        icon: useSolarIcon('sun-2'),
        type: 'checkbox',
        checked: colorMode.value === 'light',
        onSelect(e: Event) {
          e.preventDefault()

          colorMode.preference = 'light'
        }
      }, {
        label: 'Dark',
        icon: useSolarIcon('moon'),
        type: 'checkbox',
        checked: colorMode.value === 'dark',
        onUpdateChecked(checked: boolean) {
          if (checked) {
            colorMode.preference = 'dark'
          }
        },
        onSelect(e: Event) {
          e.preventDefault()
        }
      }]
    }
  ],
  ...(userIsSuperAdmin.value
    ? [
        [
          {
            label: t('account.siteAdmin'),
            icon: useSolarIcon('settings-minimalistic'),
            to: localePath('/dashboard/admin')
          }
        ]
      ]
    : []),
  [{
    label: t('auth.logout'),
    icon: useSolarIcon('logout'),
    onSelect: async () => {
      await signOut({ redirectTo: localePath('/auth') })
      toast.add({
        title: t('auth.toastSignedOut')
      })
    }
  }]]))
</script>

<template>
  <div :class="[collapsed ? 'w-8' : 'w-full h-12']">
    <UDropdownMenu
      v-if="user"
      :items="items"
      :content="{ align: 'center', collisionPadding: 12 }"
      :ui="{ content: collapsed ? 'w-48' : 'w-(--reka-dropdown-menu-trigger-width)' }"
    >
      <UButton
        v-bind="{
          ...user,
          label: collapsed ? undefined : user?.name,
          trailingIcon: collapsed ? undefined : 'i-lucide-chevrons-up-down'
        }"
        :avatar="{
          src: fallbackAvatarSrc,
          size: 'xs' as const,
          alt: user?.name
        }"
        color="neutral"
        variant="ghost"
        :block="!collapsed"
        :square="collapsed"
        class="data-[state=open]:bg-elevated"
        :ui="{
          trailingIcon: 'text-dimmed'
        }"
      />
    </UDropdownMenu>
    <UButton
      v-else
      :icon="showLoginButton ? 'i-solar-login-2-bold-duotone' : 'svg-spinners:pulse-rings-2'"
      :to="showLoginButton ? '/auth' : '#'"
      color="neutral"
      variant="ghost"
      :block="!collapsed"
      :square="collapsed"
      :class="[collapsed && 'mx-2']"
    />
  </div>
</template>
