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

const props = defineProps<{
  selectedAgents: string[]
  activeOnly?: boolean
}>()
const emit = defineEmits<{
  (e: 'update:selectedAgents', value: string[]): void
}>()

const { agents: allAgents, activeAgents, loading, fetchAgents } = useAgents()
onMounted(() => fetchAgents())

const buttonLabel = 'Agents'

/* 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) => !props.selectedAgents.includes(a.id))
    .filter((a) => {
      // In normal mode, only show agents with published versions
      // Draft agents are only available in edit page (handled by parent)
      if (a.published_at || a.status === undefined) {
        return true // Published or enterprise agent
      }
      return false // No published version
    })
)

// --- Sectioned lists ---
const favoriteIds = usePrefStore().favoriteAgents

const enterpriseAgents = computed(() =>
  availableAgents.value.filter((a) => a.isEnterprise && !favoriteIds[a.id])
)
const myAgents = computed(() =>
  availableAgents.value.filter((a) => !a.isEnterprise && !a.isShared && !favoriteIds[a.id])
)
const sharedAgents = computed(() =>
  availableAgents.value.filter((a) => a.isShared && !favoriteIds[a.id])
)
const favoriteAgents = computed(() =>
  availableAgents.value.filter((a) => favoriteIds[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)
)

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)
}
</script>

<template>
  <!-- When no more agents can be selected, show disabled button with tooltip -->
  <template v-if="availableAgents.length === 0">
    <Tooltip>
      <TooltipTrigger asChild>
        <Button variant="outline" disabled class="flex items-center px-3">
          <i class="dku-icon-ai-agent-16 mr-1" />
          <span>{{ buttonLabel }}</span>
        </Button>
      </TooltipTrigger>
      <TooltipContent>No agents are available</TooltipContent>
    </Tooltip>
  </template>

  <!-- Normal dropdown when some agents remain to be selected -->
  <template v-else>
    <DropdownMenu>
      <DropdownMenuTrigger asChild class="h-[36px]">
        <Button
          variant="outline"
          class="flex items-center data-[state=open]:border-primary data-[state=open]:ring-primary px-3"
        >
          <i class="dku-icon-ai-agent-16 mr-1" />
          <span>{{ buttonLabel }}</span>
        </Button>
      </DropdownMenuTrigger>

      <DropdownMenuContent class="w-[292px]">
        <template v-if="loading">
          <DropdownMenuItem disabled>Loading…</DropdownMenuItem>
        </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>
                  {{ agent.name }}
                </div>
                <button
                  @click.stop="removeAgent(agent.id)"
                  class="flex items-center"
                  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>
      </DropdownMenuContent>
    </DropdownMenu>
  </template>
</template>
