<template>
  <div class="shrink-0 pb-3 bg-white">
    <div class="max-w-3xl mx-auto">
      <div
        v-if="selectedAgents.length || showLiveProgressChip"
        class="mb-1 flex justify-between items-center h-[32px]"
      >
        <!-- selected-agent chips -->
        <div>
          <!-- SINGLE selection -->
          <template v-if="selectedAgents.length === 1 && !chatDisabled">
            <Badge :class="chipClasses(selectedAgents[0])" class="text-sm my-0">
              <i class="dku-icon-ai-agent-12" />
              <span>Chat with {{ getAgentName(selectedAgents[0]) }}</span>
              <AgentStatusBadge
                v-if="isAgentDeleted(selectedAgents[0], allAgents)"
                status="deleted"
                class="ml-1"
              />
              <AgentStatusBadge
                v-else-if="!isAgentActive(selectedAgents[0], allAgents) || useDraft"
                status="draft"
                class="ml-1"
              />
            </Badge>
          </template>

          <!-- MULTI selection -->
          <template v-else-if="selectedAgents.length > 1">
            <Tooltip>
              <TooltipTrigger asChild>
                <Badge class="cursor-default text-sm" :class="summaryChipClass">
                  <i class="dku-icon-ai-agent-12" />
                  <span>Chat with {{ selectedAgents.length }} agents</span>

                  <!-- draft count badge -->
                  <AgentStatusBadge
                    v-if="draftCount > 0"
                    status="draft"
                    class="ml-1"
                    :label="`${draftCount} draft${draftCount > 1 ? 's' : ''}`"
                  />

                  <!-- deleted count badge -->
                  <AgentStatusBadge
                    v-if="deletedCount > 0"
                    status="deleted"
                    class="ml-1"
                    :label="`${deletedCount} deleted${deletedCount > 1 ? 's' : ''}`"
                  />
                </Badge>
              </TooltipTrigger>

              <TooltipContent side="top" hide-arrow class="w-[300px]">
                <div class="space-y-1">
                  <div
                    v-for="id in selectedAgents"
                    :key="id"
                    class="flex items-center space-x-2 text-sm"
                    :class="[isAgentActive(id, allAgents) ? '' : 'opacity-60']"
                  >
                    <i :class="getAgentTypeIcon(id)" />
                    <span>{{ getAgentName(id) }}</span>
                    <AgentStatusBadge v-if="isAgentDeleted(id, allAgents)" status="deleted" />
                    <AgentStatusBadge v-else-if="!isAgentActive(id, allAgents)" status="draft" />
                  </div>
                </div>
              </TooltipContent>
            </Tooltip>
          </template>
        </div>

        <!-- live-progress chip -->
        <Button
          variant="ghost"
          @click="onOpenEventLog"
          v-if="showLiveProgressChip"
          class="ml-auto text-foreground max-w"
        >
          <i :class="[lastLiveEventInfo?.icon, 'text-primary']"></i>
          <span
            v-html="lastLiveEventInfo?.label"
            class="truncate max-w-[200px] sm:max-w-[200px] lg:max-w-[300px] lightwave"
          ></span>
        </Button>

        <label
          v-if="showSelectedAgentExamplesToggle && !chatDisabled && exampleQuestions?.length"
          class="flex items-center cursor-pointer select-none"
        >
          <span class="text-sm text-foreground mr-2 hidden sm:inline">Show examples</span>
          <Switch v-model="switchEnabled" />
        </label>
      </div>
      <div
        v-if="
          !selectedAgents.length &&
          !showLiveProgressChip &&
          (exampleQuestions?.length || route.name == 'Home')
        "
        class="mb-1 flex justify-between items-center h-[32px]"
        aria-hidden="true"
      ></div>

      <Tooltip>
        <TooltipTrigger asChild>
          <!-- Input box -->
          <Card
            class="py-2 px-3 rounded-md shadow-none focus-within:border-primary transition-colors"
            :class="{ 'bg-muted hover:bg-[#dcdcde]': chatDisabled }"
          >
            <div class="flex flex-col space-y-2">
              <Textarea
                ref="textareaRef"
                v-model="newMessage"
                autofocus
                :placeholder="inputPlaceholder"
                :disabled="chatDisabled || hasDeletedSelected"
                rows="4"
                class="w-full resize-none p-0 placeholder:text-sm rounded-none max-h-[35vh]"
                @keydown.enter.exact="onEnterKey"
              />
              <div class="flex items-center justify-between">
                <div class="flex items-center gap-2">
                  <AgentSelector
                    v-if="!disableAgentSelection"
                    v-model:selectedAgents="selectedAgents"
                    :activeOnly="activeOnlyAgents"
                  />
                  <LlmSelector
                    v-if="showLlmSettings"
                    customClass="max-w-[139px] hover:bg-accent"
                    hideChevron
                  >
                    <template #icon>
                      <i class="dku-icon-llm-16"></i>
                    </template>
                  </LlmSelector>
                </div>
                <div />
                <template v-if="!isStreaming">
                  <Button
                    @click="handleSend"
                    :disabled="chatDisabled || hasDeletedSelected"
                    :class="sendButtonClasses"
                  >
                    <i class="dku-icon-arrow-right-20"></i>
                  </Button>
                </template>
                <template v-else>
                  <Button @click="cancelStream">
                    <i class="dku-icon-square-circle-outline-16 text-xl"></i>
                  </Button>
                </template>
              </div>
            </div>
          </Card>
        </TooltipTrigger>
        <TooltipContent v-if="chatDisabled" hide-arrow>
          Fill in the instructions to test the agent
        </TooltipContent>
      </Tooltip>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, nextTick, watch } from 'vue'
import AgentStatusBadge from '@/components/AgentStatusBadge.vue'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { Card } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import AgentSelector from './AgentSelector.vue'
import { isAgentActive, isAgentDeleted } from '@/composables/useAgents'
import LlmSelector from './LlmSelector.vue'
import { Switch } from '@/components/ui/switch'
import { usePrefStore } from '@/store/prefStore'
import { useConversationStore } from '@/store/conversationStore'
import { Tooltip, TooltipTrigger, TooltipContent } from './ui/tooltip'
import type { SuggestedExample } from '@/types/agent'

const props = defineProps<{
  selectedAgents: string[]
  allAgents: any[]
  isStreaming: boolean
  chatDisabled: boolean
  hasDeletedSelected: boolean
  inputPlaceholder: string
  disableAgentSelection?: boolean
  activeOnlyAgents?: boolean
  showLiveProgressChip?: boolean
  lastLiveEventInfo?: { label: string; icon: any }
  activeEventLogMessageId?: string | null
  openEventLogPanel?: (msg: any) => void
  hideExampleToggle?: boolean
  exampleQuestions?: SuggestedExample[]
  useDraft?: boolean
}>()

const emits = defineEmits<{
  (e: 'update:selectedAgents', v: string[]): void
  (e: 'send', message: string): void
  (e: 'cancel'): void
  (e: 'update:hasContent', hasContent: boolean): void
}>()

const prefStore = usePrefStore()
const switchEnabled = computed({
  get: () => prefStore.showChatExamples,
  set: (v) => prefStore.setShowChatExamples(v),
})
import { useRoute } from 'vue-router'
import { WT1iser } from '@/lib/wt1'
const route = useRoute()

const conversationStore = useConversationStore()
const showSelectedAgentExamplesToggle = computed(() => {
  if (props.hideExampleToggle || conversationStore.isActiveConversationInitializing) return false
  return (
    selectedAgents.value.length > 0 && !props.isStreaming && conversationStore.showAgentPromptState
  )
})

const showLlmSettings = ref(false)

/* -------------------------------------------------------------------------------- */
const newMessage = ref('')

watch(
  () => newMessage.value,
  (newVal) => {
    emits('update:hasContent', newVal.trim().length > 0)
  },
  { immediate: true }
)

const selectedAgents = computed({
  get: () => props.selectedAgents,
  set: (v: string[]) => emits('update:selectedAgents', v),
})
const textareaRef = ref<{ focus?: () => void } | null>(null)

function focusInput() {
  // If disabled, focus won’t work anyway, but safe to call
  nextTick(() => textareaRef.value?.focus?.())
}

function setMessage(text: string) {
  newMessage.value = text
  nextTick(() => focusInput())
}

defineExpose({ focusInput, setMessage })

/* -------------------------------------------------------------------------------- */
// Actions
function handleSend() {
  if (!props.isStreaming && newMessage.value.trim()) {
    const messageToSend = newMessage.value.trim()
    WT1iser.askQuestion()
    emits('send', messageToSend)
    newMessage.value = ''
  }
}

function onEnterKey(e: KeyboardEvent) {
  const canSend =
    !props.isStreaming && !props.chatDisabled && !props.hasDeletedSelected && hasContentToSend.value

  if (canSend) {
    const messageToSend = newMessage.value.trim()
    WT1iser.askQuestion()
    e.preventDefault()
    emits('send', messageToSend)
    newMessage.value = ''
  }
}

function cancelStream() {
  emits('cancel')
}
function onOpenEventLog() {
  if (props.openEventLogPanel) {
    WT1iser.messageViewEventLog()
    props.openEventLogPanel({ id: props.activeEventLogMessageId } as any)
  }
}

/* -------------------------------------------------------------------------------- */
// Helpers
function getAgentName(id: string) {
  let agent: any
  if (Array.isArray(props.allAgents)) {
    const agents = props.allAgents.filter((a: any) => a.id === id)
    if (agents.length > 1) {
      if (props.useDraft) {
        agent = agents.find((a: any) => a.status === 'draft')
      } else {
        agent = agents.find((a: any) => a.status === 'active')
      }
    } else {
      agent = agents[0]
    }
  } else {
    // Fallback in case a Map is provided
    agent = (props.allAgents as any)?.get?.(id)
  }
  return agent?.name ?? id
}

function getAgentTypeIcon(id: string) {
  let agent: any
  if (Array.isArray(props.allAgents)) {
    agent = props.allAgents.find((a: any) => a.id === id)
  } else {
    // Fallback in case a Map is provided
    agent = (props.allAgents as any)?.get?.(id)
  }
  if (agent?.isEnterprise) return 'dku-icon-briefcase-16'
  if (agent?.isShared) return 'dku-icon-share-16'
  return 'dku-icon-user-16'
}

function chipClasses(id: string) {
  if (isAgentDeleted(id, props.allAgents)) return ''
  return isAgentActive(id, props.allAgents) && !props.useDraft ? '' : 'bg-[#D4D4D8] text-foreground'
}

/* -------------------------------------------------------------------------------- */
// Counts & classes
const deletedCount = computed(
  () => selectedAgents.value.filter((id) => isAgentDeleted(id, props.allAgents)).length
)
const draftCount = computed(
  () =>
    selectedAgents.value.filter(
      (id) => !isAgentDeleted(id, props.allAgents) && !isAgentActive(id, props.allAgents)
    ).length
)
const summaryChipClass = computed(() => 'bg-primary text-primary-foreground')

/* -------------------------------------------------------------------------------- */
// Send button state
const hasContentToSend = computed(() => {
  return newMessage.value.trim().length > 0
})

const sendButtonClasses = computed(() => {
  if (hasContentToSend.value) {
    return 'px-2 bg-primary text-white hover:bg-primary-hover active:bg-primary-selected'
  }
  return 'px-2 hover:bg-primary-foreground bg-primary-foreground text-muted-foreground'
})
</script>

<style scoped>
/* No additional scoped styles */
</style>
<style>
[data-state='open'] .chevron-icon {
  transform: rotate(180deg);
}
</style>
