<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import {
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuLabel,
} from '@/components/ui/dropdown-menu'
import { Button } from '@/components/ui/button'
import { Switch } from '@/components/ui/switch'
import { Tooltip, TooltipTrigger, TooltipContent } from '@/components/ui/tooltip'
import { useAgents } from '@/composables/useAgents'
import { usePrefStore } from '@/store/prefStore'
import type { SuggestedExample } from '@/types/agent'

const props = withDefaults(
  defineProps<{
    selectedAgents: string[]
    activeOnly?: boolean
    modeAgents: boolean
    selectedLlm: string | null
    showExamplesToggle?: boolean
    exampleQuestions?: SuggestedExample[]
    disabled?: boolean
    allowModeSwitching?: boolean
    modeSwitchingDisabledReason?: 'admin_disabled' | 'attachments' | 'other' | null
  }>(),
  {
    allowModeSwitching: true,
    modeSwitchingDisabledReason: null,
  }
)

const emit = defineEmits<{
  (e: 'update:selectedAgents', value: string[]): void
  (e: 'update:modeAgents', value: boolean): void
  (e: 'update:selectedLlm', value: string | null): void
}>()

const prefStore = usePrefStore()
const { agents: allAgents, activeAgents, loading } = useAgents()

// Internal state for agent mode toggle
const agentModeEnabled = computed({
  get: () => props.modeAgents,
  set: (v) => emit('update:modeAgents', v),
})

// Examples toggle state (from prefStore)
const showExamples = computed({
  get: () => prefStore.showChatExamples,
  set: (v) => prefStore.setShowChatExamples(v),
})

// Show examples toggle only when in agent mode, with agent(s) selected, and examples exist
const shouldShowExamplesToggle = computed(() => {
  return (
    props.showExamplesToggle &&
    agentModeEnabled.value &&
    props.selectedAgents.length > 0 &&
    props.exampleQuestions &&
    props.exampleQuestions.length > 0
  )
})

// Button label changes based on mode
const buttonLabel = computed(() => (agentModeEnabled.value ? 'Agents' : 'LLM'))
const buttonIcon = computed(() =>
  agentModeEnabled.value ? 'dku-icon-ai-agent-16' : 'dku-icon-llm-16'
)

/* pick the right source list */
const source = computed(() => (props.activeOnly ? activeAgents.value : allAgents.value))

/* list shown in dropdown */
const availableAgents = computed(() =>
  source.value.filter((a) => {
    // In normal mode, only show agents with published versions
    if (a.published_at || a.status === undefined) {
      return true // Published or enterprise agent
    }
    return false // No published version
  })
)

// --- Sectioned lists for agents ---
const favoriteIds = computed(() => prefStore.favoriteAgents)

const enterpriseAgents = computed(() =>
  availableAgents.value.filter((a) => a.isEnterprise && !favoriteIds.value[a.id])
)
const myAgents = computed(() =>
  availableAgents.value.filter((a) => !a.isEnterprise && !a.isShared && !favoriteIds.value[a.id])
)
const sharedAgents = computed(() =>
  availableAgents.value.filter((a) => a.isShared && !favoriteIds.value[a.id])
)
const favoriteAgents = computed(() =>
  availableAgents.value.filter((a) => favoriteIds.value[a.id] === true)
)

const sections = computed(() =>
  [
    { label: 'Favorite Agents', icon: 'dku-icon-star-outline-16', items: favoriteAgents.value },
    { label: 'Enterprise Agents', icon: 'dku-icon-briefcase-16', items: enterpriseAgents.value },
    { label: 'My Agents', icon: 'dku-icon-user-16', items: myAgents.value },
    { label: 'Agents shared with me', icon: 'dku-icon-share-16', items: sharedAgents.value },
  ].filter((s) => s.items.length > 0)
)

// --- LLM selection ---
const llmList = computed(() => prefStore.aHLlms || [])
const defaultLlm = computed(() => prefStore.uiConf?.default_llm || prefStore.baseLlmid || '')

const selectedLlmId = computed({
  get: () => props.selectedLlm ?? defaultLlm.value,
  set: (v) => emit('update:selectedLlm', v),
})

// Watch for mode changes and auto-select first LLM when switching from agent mode to LLM mode
watch(
  () => props.modeAgents,
  (newValue, oldValue) => {
    // When switching from agent mode (true) to LLM mode (false)
    if (oldValue === true && newValue === false && llmList.value.length > 0) {
      const firstLlm = llmList.value[0]
      if (firstLlm) {
        emit('update:selectedLlm', firstLlm.id)
      }
    }
  }
)

function selectAgent(id: string) {
  if (props.selectedAgents.includes(id)) {
    removeAgent(id)
    return
  }
  emit('update:selectedAgents', [...props.selectedAgents, id])
}

function removeAgent(id: string) {
  const filteredAgents = props.selectedAgents.filter((x) => x !== id)
  emit('update:selectedAgents', filteredAgents)
}

// Determine if the button should be disabled
const isButtonDisabled = computed(() => {
  if (props.disabled) return true
  if (agentModeEnabled.value && availableAgents.value.length === 0) return true
  if (!agentModeEnabled.value && llmList.value.length === 0) return true
  return false
})

// Keep dropdown open state to handle switch clicks without closing
const dropdownOpen = ref(false)

// Tooltip message based on why mode switching is disabled
const modeSwitchingTooltipMessage = computed(() => {
  if (props.modeSwitchingDisabledReason === 'attachments') {
    return "Agents aren't available in conversations that include attachments"
  }
  return "Agents aren't available"
})

// Whether to show the mode switching toggle (hide if admin disabled)
const showModeSwitchingToggle = computed(() => {
  return props.modeSwitchingDisabledReason !== 'admin_disabled'
})
</script>

<template>
  <!-- Disabled state with tooltip -->
  <template v-if="isButtonDisabled && !disabled">
    <Tooltip>
      <TooltipTrigger asChild>
        <Button variant="outline" disabled class="flex items-center px-3">
          <i :class="[buttonIcon, 'mr-1']" />
          <span>{{ buttonLabel }}</span>
        </Button>
      </TooltipTrigger>
      <TooltipContent>
        {{ agentModeEnabled ? 'No agents are available' : 'No LLMs are available' }}
      </TooltipContent>
    </Tooltip>
  </template>

  <!-- Normal dropdown -->
  <template v-else>
    <DropdownMenu v-model:open="dropdownOpen">
      <DropdownMenuTrigger asChild class="h-[36px]">
        <Button
          variant="outline"
          :disabled="disabled"
          class="flex items-center data-[state=open]:border-primary data-[state=open]:ring-primary px-3"
        >
          <i :class="[buttonIcon, 'mr-1']" />
          <span>{{ buttonLabel }}</span>
        </Button>
      </DropdownMenuTrigger>

      <DropdownMenuContent class="w-[292px]" side="top">
        <!-- Fixed toggles section at top -->
        <div
          v-if="showModeSwitchingToggle"
          class="sticky top-0 bg-popover z-10 border-b border-border pb-2 mb-1"
        >
          <!-- Agent mode toggle -->
          <Tooltip>
            <TooltipTrigger asChild>
              <div
                class="flex items-center justify-between px-2 py-2 rounded-sm"
                :class="{ 'cursor-pointer hover:bg-accent': allowModeSwitching }"
                @click.stop="allowModeSwitching && (agentModeEnabled = !agentModeEnabled)"
              >
                <div class="flex items-center">
                  <span class="text-sm font-medium" :class="{ 'opacity-50': !allowModeSwitching }"
                    >Enable agents</span
                  >
                </div>
                <Switch
                  :disabled="!allowModeSwitching"
                  :model-value="agentModeEnabled"
                  @update:model-value="agentModeEnabled = $event"
                  @click.stop
                />
              </div>
            </TooltipTrigger>
            <TooltipContent v-if="!allowModeSwitching" hide-arrow>
              {{ modeSwitchingTooltipMessage }}
            </TooltipContent>
          </Tooltip>
        </div>

        <!-- Examples toggle (only when applicable) -->
        <div
          v-if="shouldShowExamplesToggle"
          class="flex items-center justify-between px-2 py-2 hover:bg-accent rounded-sm cursor-pointer"
          @click.stop="showExamples = !showExamples"
        >
          <div class="flex items-center">
            <span class="text-sm font-medium">Show examples</span>
          </div>
          <Switch
            :model-value="showExamples"
            @update:model-value="showExamples = $event"
            @click.stop
          />
        </div>

        <!-- Agent selection (when in agent mode) -->
        <template v-if="agentModeEnabled">
          <template v-if="loading">
            <DropdownMenuItem disabled>Loading…</DropdownMenuItem>
          </template>
          <template v-else-if="sections.length === 0">
            <div class="px-2 py-3 text-sm text-muted-foreground text-center">
              No agents available
            </div>
          </template>
          <template v-else>
            <template v-for="(section, index) in sections" :key="section.label">
              <DropdownMenuLabel class="text-foreground/70 flex items-center font-semibold">
                <i :class="section.icon" class="mr-2" />
                {{ section.label }}
              </DropdownMenuLabel>
              <DropdownMenuItem
                v-for="agent in section.items"
                :key="agent.id"
                @select.prevent="selectAgent(agent.id)"
                class="cursor-pointer"
              >
                <div class="flex items-center justify-between w-full">
                  <div class="truncate">
                    {{ agent.name }}
                  </div>
                  <button
                    @click.stop="removeAgent(agent.id)"
                    class="flex items-center shrink-0"
                    v-if="props.selectedAgents.includes(agent.id)"
                  >
                    <i class="dku-icon-checkmark-16" />
                  </button>
                </div>
              </DropdownMenuItem>
              <DropdownMenuSeparator v-if="index < sections.length - 1" />
            </template>
          </template>
        </template>

        <!-- LLM selection (when not in agent mode) -->
        <template v-else>
          <template v-if="llmList.length === 0">
            <div class="px-2 py-3 text-sm text-muted-foreground text-center">No LLMs available</div>
          </template>
          <template v-else>
            <DropdownMenuItem v-for="llm in llmList" :key="llm.id">
              <div class="flex items-center justify-between w-full">
                <div class="truncate">
                  {{ llm.shortName }}
                </div>
                <i
                  v-if="selectedLlmId === llm.id"
                  class="dku-icon-circle-fill-12 text-foreground shrink-0"
                />
              </div>
            </DropdownMenuItem>
          </template>
        </template>
      </DropdownMenuContent>
    </DropdownMenu>
  </template>
</template>
