<script setup lang="ts">
import { computed, ref } from 'vue'
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Input } from '@/components/ui/input'
import { ScrollArea } from '@/components/ui/scroll-area'

interface Folder {
  id: string
  name: string
  path: string
  level: number
  hasChildren: boolean
}

interface Props {
  modelValue?: string
  folders: Folder[]
  placeholder?: string
  disabled?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  placeholder: 'Select a folder',
  disabled: false,
})

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

const searchQuery = ref('')
const isOpen = ref(false)

const filteredFolders = computed(() => {
  const query = searchQuery.value.toLowerCase().trim()
  if (!query) return props.folders

  return props.folders.filter((folder) => {
    return folder.name.toLowerCase().includes(query) || folder.path.toLowerCase().includes(query)
  })
})

const selectedFolderDisplay = computed(() => {
  if (!props.modelValue) return null
  const folder = props.folders.find((f) => f.id === props.modelValue)
  return folder ? folder.path : props.modelValue
})

function getIndentation(level: number): string {
  return '\u00A0\u00A0'.repeat(level)
}

function getFolderIcon(folder: Folder): string {
  if (folder.id === 'ROOT') return 'dku-icon-folder-16'
  return folder.hasChildren ? 'dku-icon-folder-16' : 'dku-icon-folder-outline-16'
}

function handleSelect(value: unknown) {
  if (typeof value === 'string' && value) {
    emit('update:modelValue', value)
  }
  isOpen.value = false
  searchQuery.value = ''
}

function handleOpenChange(open: boolean) {
  isOpen.value = open
  if (!open) {
    searchQuery.value = ''
  }
}
</script>

<template>
  <Select
    :modelValue="modelValue"
    @update:modelValue="handleSelect"
    :disabled="disabled"
    @update:open="handleOpenChange"
  >
    <SelectTrigger class="w-full admin-select-trigger" :class="{ 'admin-dropdown-trigger': true }">
      <SelectValue :placeholder="placeholder">
        <span v-if="selectedFolderDisplay" class="flex items-center gap-2">
          <i class="dku-icon-folder-16 text-muted-foreground"></i>
          <span class="truncate">{{ selectedFolderDisplay }}</span>
        </span>
      </SelectValue>
    </SelectTrigger>
    <SelectContent>
      <SelectGroup>
        <!-- Search input -->
        <div class="p-2 border-b border-border">
          <Input
            v-model="searchQuery"
            placeholder="Search folders..."
            class="h-8 admin-input"
            @click.stop
            @keydown.stop
          />
        </div>

        <ScrollArea class="max-h-[300px]">
          <div class="p-1">
            <SelectItem
              v-for="folder in filteredFolders"
              :key="folder.id"
              :value="folder.id"
              class="cursor-pointer text-sm"
            >
              <div class="flex items-center gap-1.5 w-full">
                <span
                  v-if="folder.level > 0"
                  class="text-muted-foreground select-none"
                  v-html="getIndentation(folder.level)"
                ></span>

                <i
                  :class="[
                    getFolderIcon(folder),
                    'flex-shrink-0',
                    folder.id === 'ROOT' ? 'text-primary' : 'text-muted-foreground',
                  ]"
                ></i>

                <span class="truncate" :class="folder.id === 'ROOT' ? 'font-semibold' : ''">
                  {{ folder.name }}
                </span>

                <i
                  v-if="folder.hasChildren && folder.id !== 'ROOT'"
                  class="dku-icon-chevron-right-12 text-muted-foreground/50 ml-auto flex-shrink-0"
                ></i>
              </div>
            </SelectItem>

            <div
              v-if="filteredFolders.length === 0"
              class="py-6 text-center text-sm text-muted-foreground"
            >
              No folders found
            </div>
          </div>
        </ScrollArea>
      </SelectGroup>
    </SelectContent>
  </Select>
</template>
