<template>
  <AccordionItem
    :disabled="props.disabled"
    value="tools"
    class="border rounded-lg overflow-hidden data-[state=open]:border-primary data-[state=open]:border-b"
  >
    <AccordionTrigger class="p-4 hover:no-underline hover:bg-gray-100/30 transition-colors">
      <div class="flex items-center justify-between w-full">
        <div class="flex flex-col space-x-3">
          <div class="flex flex-row items-center justify-start">
            <i class="dku-icon-tool-wrench-16 text-primary mr-2 my-auto"></i>
            <div class="text-base text-base-foreground my-auto inline-flex items-center gap-2">
              <div>Tools</div>
              <Badge class="text-[#0B590B] bg-[#E7EEE7]">
                {{ modelValue.tools.length }} selected
              </Badge>
            </div>
          </div>
          <div class="ml-7">
            <p class="text-sm text-foreground mt-0.5">
              Enabling tools lets the assistant perform specific actions or access external services
              to better assist you
            </p>
          </div>
        </div>
      </div>

      <template #icon>
        <i
          class="dku-icon-chevron-down-16 text-muted-foreground pointer-events-none text-xl shrink-0 translate-y-0.5 transition-transform duration-200"
        ></i>
      </template>
    </AccordionTrigger>
    <AccordionContent class="px-4 pb-4 pt-2 bg-white">
      <div>
        <!-- Tool Selection -->
        <div class="mb-2">
          <div class="flex items-center gap-1 mb-1">
            <Label class="font-medium">Select available tools</Label>
            <Tooltip>
              <TooltipTrigger asChild>
                <i class="dku-icon-info-circle-outline-16 text-base-foreground"></i>
              </TooltipTrigger>
              <TooltipContent hideArrow>
                <p class="max-w-xs">
                  Select tools to give your agent additional capabilities like web search,
                  calculations, or API calls.
                </p>
              </TooltipContent>
            </Tooltip>
          </div>

          <!-- Multi-select dropdown -->
          <DropdownMenu :disabled="props.disabled">
            <DropdownMenuTrigger asChild>
              <Button
                variant="outline"
                class="justify-between data-[state=open]:border-primary data-[state=open]:ring-primary w-[230px]"
              >
                <span v-if="modelValue.tools.length === 0" class="text-muted-foreground">
                  Select tools...
                </span>
                <span v-else>
                  {{ modelValue.tools.length }} tool{{ modelValue.tools.length === 1 ? '' : 's' }}
                  selected
                </span>
                <i class="dku-icon-chevron-down-16" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent class="max-h-60 overflow-y-auto w-[230px]">
              <div v-for="tool in toolsStore.tools" :key="tool.id">
                <Tooltip v-if="tool.configured === false">
                  <TooltipTrigger asChild>
                    <DropdownMenuItem @click.prevent>
                      <div class="flex items-center justify-between w-full">
                        <div class="flex items-center space-x-2">
                          <span class="text-gray-400">{{ tool.name }}</span>
                          <i class="dku-icon-alert-outline-16 text-amber-500" />
                        </div>
                      </div>
                    </DropdownMenuItem>
                  </TooltipTrigger>
                  <TooltipContent hideArrow>
                    <p class="max-w-xs">
                      This tool is not properly configured and cannot be used.
                      <span v-if="tool.error" class="block mt-1 text-xs opacity-75">
                        Error: {{ tool.error }}
                      </span>
                    </p>
                  </TooltipContent>
                </Tooltip>

                <DropdownMenuItem
                  v-else
                  @click="toggleTool(tool.id)"
                  class="cursor-pointer"
                  :class="{ 'bg-accent': modelValue.tools.includes(tool.id) }"
                >
                  <div class="flex items-center justify-between w-full">
                    <span class="truncate">{{ tool.name }}</span>
                    <i
                      v-if="modelValue.tools.includes(tool.id)"
                      class="dku-icon-check-16 text-primary"
                    />
                  </div>
                </DropdownMenuItem>
              </div>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>

        <!-- Selected Tools Display -->
        <div v-if="modelValue.tools.length > 0" class="space-y-2">
          <div class="flex items-center justify-end">
            <Button @click="clearAllTools" variant="ghost">
              <i class="dku-icon-trash-16"></i>
              Delete all
            </Button>
          </div>

          <!-- Desktop: Show all tools -->
          <div v-if="!shouldShowAccordion" class="flex flex-wrap gap-2">
            <Tooltip v-for="toolId in modelValue.tools" :key="toolId">
              <TooltipTrigger asChild>
                <span
                  class="inline-flex items-center space-x-1 px-3 py-1 border rounded-md text-sm select-none transition group bg-white border-border hover:border-gray-400"
                >
                  <i class="dku-icon-tool-wrench-16" />
                  <span class="truncate max-w-[120px]">
                    {{ getToolName(toolId) }}
                  </span>
                  <button
                    @click="removeTool(toolId)"
                    class="p-0.5 rounded-md hover:bg-gray-100 transition-colors"
                  >
                    <i class="dku-icon-dismiss-16"></i>
                  </button>
                </span>
              </TooltipTrigger>
              <TooltipContent hideArrow>
                <p>{{ getToolName(toolId) }}</p>
              </TooltipContent>
            </Tooltip>
          </div>

          <!-- Mobile: Show accordion when more than 5 tools -->
          <div v-if="shouldShowAccordion" class="space-y-2">
            <!-- First 5 visible tools -->
            <div class="flex flex-wrap gap-2">
              <Tooltip v-for="toolId in visibleTools" :key="toolId">
                <TooltipTrigger asChild>
                  <span
                    class="inline-flex items-center space-x-1 px-3 py-1 border rounded-md text-sm select-none transition group bg-white border-border hover:border-gray-400 tool-badge"
                  >
                    <i class="dku-icon-tool-wrench-16" />
                    <span class="truncate max-w-[120px]">
                      {{ getToolName(toolId) }}
                    </span>
                    <button
                      @click="removeTool(toolId)"
                      class="p-0.5 rounded-xs hover:bg-gray-100 transition-colors"
                    >
                      <i class="dku-icon-dismiss-16"></i>
                    </button>
                  </span>
                </TooltipTrigger>
                <TooltipContent hideArrow>
                  <p>{{ getToolName(toolId) }}</p>
                </TooltipContent>
              </Tooltip>
            </div>

            <!-- Accordion for remaining tools -->
            <Accordion type="single" collapsible>
              <AccordionItem value="more-tools" class="border-none">
                <AccordionTrigger class="py-2 px-0 text-sm !flex-none w-fit">
                  <span class="flex items-center"> View {{ hiddenTools.length }} more </span>
                </AccordionTrigger>
                <AccordionContent class="pt-2">
                  <div class="flex flex-wrap gap-2">
                    <Tooltip v-for="toolId in hiddenTools" :key="toolId">
                      <TooltipTrigger asChild>
                        <span
                          class="inline-flex items-center space-x-1 px-3 py-1 border rounded-md text-sm select-none transition group bg-white border-border hover:border-gray-400 tool-badge"
                        >
                          <i class="dku-icon-tool-wrench-16" />
                          <span class="truncate max-w-[120px]">
                            {{ getToolName(toolId) }}
                          </span>
                          <button
                            @click="removeTool(toolId)"
                            class="p-0.5 rounded-md hover:bg-gray-100 transition-colors"
                          >
                            <i class="dku-icon-dismiss-16"></i>
                          </button>
                        </span>
                      </TooltipTrigger>
                      <TooltipContent hideArrow>
                        <p>{{ getToolName(toolId) }}</p>
                      </TooltipContent>
                    </Tooltip>
                  </div>
                </AccordionContent>
              </AccordionItem>
            </Accordion>
          </div>
        </div>

        <div class="flex justify-end">
          <Button size="sm" variant="ghost" @click.stop="openToolsAdvancedMode">
            <i class="dku-icon-gear-16 mr-1 text-primary"></i>
            <span>Advanced Mode</span>
            <i class="dku-icon-chevron-right-16"></i>
          </Button>
        </div>
      </div>
    </AccordionContent>
  </AccordionItem>

  <!-- Tools Advanced Mode -->
  <ToolsAdvancedMode
    v-if="showToolsAdvancedMode"
    :agent-name="agentName"
    :selected-tools="modelValue.tools"
    :available-tools="toolsStore.tools"
    @update:selected-tools="updateToolsFromAdvancedMode"
    @close="showToolsAdvancedMode = false"
  />
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from '@/components/ui/accordion'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import {
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuItem,
} from '@/components/ui/dropdown-menu'

import ToolsAdvancedMode from '../AgentConfiguration/Tools/ToolsAdvancedMode.vue'
import { useToolsStore } from '@/store/toolsStore'
import { WT1iser } from '@/lib/wt1'

interface Props {
  modelValue: {
    tools: string[]
  }
  agentName: string
  disabled?: boolean
}

const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: Props['modelValue']): void
}>()

const showToolsAdvancedMode = ref(false)

// Mobile accordion computed properties
const shouldShowAccordion = computed(() => modelValue.value.tools.length > 5)
const visibleTools = computed(() => {
  if (shouldShowAccordion.value) {
    return modelValue.value.tools.slice(0, 5)
  }
  return modelValue.value.tools
})
const hiddenTools = computed(() => {
  if (shouldShowAccordion.value) {
    return modelValue.value.tools.slice(5)
  }
  return []
})

// Create a computed property to handle v-model
const modelValue = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value),
})

/** Tools **/
const toolsStore = useToolsStore()

function getToolName(toolId: string): string {
  const tool = toolsStore.tools.find((t) => t.id === toolId)
  return tool ? tool.name : toolId + ' (Unknown)'
}

function toggleTool(toolId: string) {
  const newTools = [...modelValue.value.tools]
  const index = newTools.indexOf(toolId)
  if (index > -1) {
    newTools.splice(index, 1)
  } else {
    newTools.push(toolId)
  }
  // Create a new object to trigger reactivity
  modelValue.value = {
    ...modelValue.value,
    tools: newTools,
  }
}

function removeTool(toolId: string) {
  const newTools = [...modelValue.value.tools]
  const index = newTools.indexOf(toolId)
  if (index > -1) {
    newTools.splice(index, 1)
    // Create a new object to trigger reactivity
    modelValue.value = {
      ...modelValue.value,
      tools: newTools,
    }
  }
}

function clearAllTools() {
  // Create a new object with empty tools array to trigger reactivity
  modelValue.value = {
    ...modelValue.value,
    tools: [],
  }
}

function openToolsAdvancedMode() {
  WT1iser.viewToolsLibrary()
  showToolsAdvancedMode.value = true
}

function updateToolsFromAdvancedMode(tools: string[]) {
  modelValue.value = {
    ...modelValue.value,
    tools: tools,
  }
}
</script>

<style scoped></style>
