<template>
  <Transition name="fullscreen-mode">
    <div class="fixed inset-0 z-50 bg-white flex flex-col">
      <!-- Header -->
      <div class="border-b bg-gray-50 h-[56px] py-1.5 px-3 flex items-center w-full">
        <div class="flex items-center space-x-2 sm:space-x-4 min-w-0">
          <Button variant="ghost" size="sm" @click="handleClose" class="shrink-0">
            <i class="dku-icon-chevron-left-16" />
            <span>Back</span>
          </Button>
        </div>
      </div>

      <!-- Main Content -->
      <div class="flex-1 overflow-y-auto py-5 md:px-2 h-full">
        <div class="flex gap-6 h-full">
          <div
            class="space-y-6 md:border md:border-border px-2.5 md:p-5 flex-1 md:rounded-lg md:overflow-y-auto max-w-[1000px] mx-auto"
          >
            <div>
              <div class="flex items-center gap-2 mb-4">
                <i class="dku-icon-tool-wrench-16 text-primary my-auto"></i>
                <h3 class="text-xl font-semibold">Tools Library</h3>
              </div>
              <Alert variant="info" collapsible class="my-4 md:max-w-[678px]">
                <i class="dku-icon-info-circle-outline-16"></i>
                <AlertTitle>About Tools</AlertTitle>
                <AlertDescription>
                  Allow your agent to perform specific actions, use data source, leverage other
                  systems and more.
                </AlertDescription>
              </Alert>
              <Alert variant="warning" class="md:max-w-[678px]">
                <i class="dku-icon-warning-outline-16"></i>
                <AlertDescription
                  >Contact your administrator if a tool is not working as expected or if you need a
                  new tool</AlertDescription
                >
              </Alert>
              <!-- Search and Filter -->

              <div class="py-5 max-w-[320px]">
                <div class="relative">
                  <i
                    class="dku-icon-search-16 absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"
                  ></i>
                  <Input
                    v-model="searchQuery"
                    placeholder="Search"
                    class="pl-10 pr-4 py-2 w-full border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent"
                  />
                </div>
              </div>

              <!-- Tools Summary -->
              <div class="mb-6 flex items-center justify-between p-4">
                <div class="text-sm">
                  {{ localSelectedTools.length }} of {{ props.availableTools.length }} tool{{
                    props.availableTools.length > 1 ? 's' : ''
                  }}
                  selected
                </div>
                <div class="flex items-center space-x-2">
                  <label class="text-sm font-medium text-gray-700">Select all</label>
                  <Switch
                    :modelValue="isAllToolsSelected"
                    @update:modelValue="toggleAllTools"
                    class="ml-2"
                  />
                </div>
              </div>

              <!-- Tools Grid -->
              <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                <ToolCard
                  v-for="tool in filteredTools"
                  :key="tool.id"
                  :tool="tool"
                  :is-selected="localSelectedTools.includes(tool.id)"
                  @toggle="toggleTool(tool.id)"
                />
              </div>

              <!-- Empty state -->
              <div v-if="filteredTools.length === 0" class="text-center py-12">
                <p class="text-gray-500 text-lg">
                  {{ searchQuery ? 'No tools found matching your search.' : 'No tools available.' }}
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </Transition>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import ToolCard from './ToolCard.vue'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Switch } from '@/components/ui/switch'

// Props
const props = defineProps<{
  agentName: string
  selectedTools: string[]
  availableTools: Array<{
    id: string
    name: string
    description: string
    type: string
  }>
}>()

const emit = defineEmits<{
  (e: 'update:selected-tools', value: string[]): void
  (e: 'close'): void
}>()

const searchQuery = ref('')
const localSelectedTools = ref<string[]>([...props.selectedTools])

watch(
  () => props.selectedTools,
  (newTools) => {
    localSelectedTools.value = [...newTools]
  },
  { immediate: true }
)

const filteredTools = computed(() => {
  const query = (searchQuery.value || '').toLowerCase()
  if (!query) return props.availableTools

  return props.availableTools.filter((tool) => {
    const name = tool.name?.toLowerCase() || ''
    const description = tool.description?.toLowerCase() || ''
    return name.includes(query) || description.includes(query)
  })
})

const isAllToolsSelected = computed(() => {
  // Check if all filtered tools are selected
  const filteredToolIds = filteredTools.value.map((tool) => tool.id)
  return (
    filteredToolIds.length > 0 &&
    filteredToolIds.every((id) => localSelectedTools.value.includes(id))
  )
})

function handleClose() {
  emit('close')
}

function toggleTool(toolId: string) {
  const index = localSelectedTools.value.indexOf(toolId)
  if (index >= 0) {
    localSelectedTools.value.splice(index, 1)
  } else {
    localSelectedTools.value.push(toolId)
  }
  emit('update:selected-tools', [...localSelectedTools.value])
}

function toggleAllTools(checked: boolean) {
  if (checked) {
    // Only activate filtered tools
    const filteredToolIds = filteredTools.value.map((tool) => tool.id)
    // Add filtered tools that aren't already selected
    filteredToolIds.forEach((toolId) => {
      if (!localSelectedTools.value.includes(toolId)) {
        localSelectedTools.value.push(toolId)
      }
    })
  } else {
    // Only deactivate filtered tools
    const filteredToolIds = filteredTools.value.map((tool) => tool.id)
    localSelectedTools.value = localSelectedTools.value.filter(
      (toolId) => !filteredToolIds.includes(toolId)
    )
  }
  emit('update:selected-tools', [...localSelectedTools.value])
}
</script>

<style scoped>
.fullscreen-mode-enter-active,
.fullscreen-mode-leave-active {
  transition: all 0.3s ease;
}

.fullscreen-mode-enter-from {
  opacity: 0;
  transform: translateY(20px);
}

.fullscreen-mode-leave-to {
  opacity: 0;
  transform: translateY(20px);
}
</style>
