<script setup lang="ts">
import { computed, ref, onMounted, watch } from 'vue'
import { useAdminConfigStore } from '@/store/adminConfigStore'
import type { Prompt, PromptsLibrary } from '@/types/admin-config'
import { getUser } from '@/lib/utils'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { Switch } from '@/components/ui/switch'
import { Label } from '@/components/ui/label'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { useSidebar } from '@/components/ui/sidebar'
import PromptCardAdmin from './PromptCardAdmin.vue'
import SelectedPromptCardAdmin from './SelectedPromptCardAdmin.vue'

const store = useAdminConfigStore()
const { isTablet, isMobile } = useSidebar()

// Mobile overlay state
const isMobileDetailOpen = ref(false)

const currentUserEmail = getUser()?.email || ''

const isPromptEnabled = (promptId: string): boolean => store.isPromptEnabled(promptId)
function togglePromptEnabled(promptId: string) {
  const enabledNow = store.isPromptEnabled(promptId)
  store.setPromptEnabled(promptId, !enabledNow)
}

const libraryPrompts = computed<Prompt[]>(() => store.draftLibrary?.prompts ?? [])

const sortedPrompts = computed<Prompt[]>(() => {
  const prompts = libraryPrompts.value
  return [...prompts].sort((a, b) => a.name.localeCompare(b.name))
})

const selectedPromptId = ref<string | null>(null)
const selectedPrompt = computed(() => {
  if (!selectedPromptId.value) return null
  return sortedPrompts.value.find((p) => p.id === selectedPromptId.value) || null
})

const searchQuery = ref('')
const selectedCategories = ref<string[]>([])
const selectedTags = ref<string[]>([])
const selectedStatus = ref<('enabled' | 'disabled')[]>(['enabled', 'disabled'])
const selectedCreators = ref<string[]>([])

// Dropdown open states for chevron rotation
const categoriesDropdownOpen = ref(false)
const tagsDropdownOpen = ref(false)
const statusDropdownOpen = ref(false)
const creatorsDropdownOpen = ref(false)

const DATAIKU_CREATOR = 'Dataiku'
const UNKNOWN_USER = 'User'

function getPromptCreator(prompt: Prompt): string {
  if (prompt.createdBy) return prompt.createdBy
  return prompt.isDefault ? DATAIKU_CREATOR : UNKNOWN_USER
}

const allCreators = computed(() => {
  const creators = new Set<string>()
  for (const p of libraryPrompts.value) {
    creators.add(getPromptCreator(p))
  }
  return Array.from(creators).sort((a, b) => {
    // Put Dataiku first, Unknown user last, then sort alphabetically
    if (a === DATAIKU_CREATOR) return -1
    if (b === DATAIKU_CREATOR) return 1
    if (a === UNKNOWN_USER) return 1
    if (b === UNKNOWN_USER) return -1
    return a.localeCompare(b)
  })
})

const allCategories = computed(() => {
  const cats = new Set<string>()
  for (const p of libraryPrompts.value) {
    if (p.category) cats.add(p.category)
  }
  return Array.from(cats).sort()
})

const allTags = computed(() => {
  const tags = new Set<string>()
  for (const p of libraryPrompts.value) {
    if (p.tags) {
      p.tags.forEach((t) => tags.add(t))
    }
  }
  return Array.from(tags).sort()
})

const filteredPrompts = computed(() => {
  let prompts = sortedPrompts.value

  if (searchQuery.value) {
    const q = searchQuery.value.toLowerCase()
    prompts = prompts.filter(
      (p) =>
        p.name.toLowerCase().includes(q) ||
        p.description.toLowerCase().includes(q) ||
        (p.tags || []).some((t) => t.toLowerCase().includes(q)) ||
        p.prompt.toLowerCase().includes(q)
    )
  }

  if (selectedCategories.value.length > 0) {
    prompts = prompts.filter((p) => selectedCategories.value.includes(p.category))
  }

  if (selectedTags.value.length > 0) {
    prompts = prompts.filter((p) => p.tags.some((t) => selectedTags.value.includes(t)))
  }

  // Status filter - only filter if not all statuses are selected
  if (selectedStatus.value.length === 1) {
    const showEnabled = selectedStatus.value.includes('enabled')
    prompts = prompts.filter((p) => isPromptEnabled(p.id) === showEnabled)
  }

  // Created by filter - only filter if some creators are selected
  if (selectedCreators.value.length > 0) {
    prompts = prompts.filter((p) => selectedCreators.value.includes(getPromptCreator(p)))
  }

  return prompts
})

// When categories are selected, group by category; otherwise show flat list
const shouldGroupByCategory = computed(() => selectedCategories.value.length > 0)

const groupedPrompts = computed(() => {
  if (!shouldGroupByCategory.value) {
    return { '': filteredPrompts.value }
  }

  const groups: Record<string, Prompt[]> = {}
  filteredPrompts.value.forEach((p) => {
    const cat = p.category || 'Uncategorized'
    if (!groups[cat]) groups[cat] = []
    groups[cat].push(p)
  })

  return groups
})

const expandedGroups = ref<Record<string, boolean>>({})

function isGroupExpanded(groupName: string): boolean {
  return expandedGroups.value[groupName] ?? false
}

const isEditing = ref(false)
const editingPrompt = ref<Prompt | null>(null)

const tagsInput = computed({
  get: () => editingPrompt.value?.tags.join(', ') || '',
  set: (value: string | number) => {
    if (editingPrompt.value) {
      editingPrompt.value.tags = String(value)
        .split(',')
        .map((t) => t.trim())
        .filter(Boolean)
    }
  },
})

const deleteDialogOpen = ref(false)
const promptToDelete = ref<string | null>(null)

function selectPrompt(prompt: Prompt) {
  if (isEditing.value) {
    const confirmDiscard = window.confirm('You have unsaved changes. Discard them?')
    if (!confirmDiscard) return
    isEditing.value = false
  }
  selectedPromptId.value = prompt.id

  // Open overlay on mobile/tablet
  if (isMobile.value || isTablet.value) {
    isMobileDetailOpen.value = true
  }
}

function closeMobileDetail() {
  isMobileDetailOpen.value = false
}

function startEditing() {
  if (selectedPrompt.value) {
    editingPrompt.value = JSON.parse(JSON.stringify(selectedPrompt.value))
    isEditing.value = true
  }
}

function cancelEditing() {
  isEditing.value = false
  editingPrompt.value = null
}

async function savePrompt() {
  if (!editingPrompt.value || !store.draftLibrary?.prompts) return
  const idx = store.draftLibrary.prompts.findIndex((p) => p.id === editingPrompt.value!.id)
  if (idx !== -1) {
    editingPrompt.value.updatedAt = new Date().toISOString()
    const promptToSave = { ...editingPrompt.value } as any
    delete promptToSave.enabled
    store.draftLibrary.prompts[idx] = promptToSave as Prompt

    try {
      await store.saveLibrary()
      isEditing.value = false
      editingPrompt.value = null
    } catch (e) {
      console.error('Failed to save prompt:', e)
      alert('Failed to save prompt. Please try again.')
    }
  }
}

async function createNewPrompt() {
  const lib = (store.draftLibrary ??= { version: '1.0.0', prompts: [] } as any) as PromptsLibrary
  const newPrompt: Prompt = {
    id: `prompt-${Date.now()}`,
    name: 'New Prompt',
    description: '',
    prompt: '',
    category: 'General',
    tags: [],
    isDefault: false,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
    createdBy: currentUserEmail || undefined,
  }
  lib.prompts.push(newPrompt)
  try {
    await store.saveLibrary()
    selectedPromptId.value = newPrompt.id
    // Open mobile overlay if on mobile/tablet
    if (isMobile.value || isTablet.value) {
      isMobileDetailOpen.value = true
    }
    startEditing()
  } catch (e) {
    console.error('Failed to create prompt:', e)
    alert('Failed to create prompt. Please try again.')
  }
}

async function duplicatePrompt() {
  if (!selectedPrompt.value) return
  const lib = (store.draftLibrary ??= { version: '1.0.0', prompts: [] } as any) as PromptsLibrary
  const original = selectedPrompt.value
  const newPrompt: Prompt = {
    id: `prompt-${Date.now()}`,
    name: `Copy of ${original.name}`,
    description: original.description,
    prompt: original.prompt,
    category: original.category,
    tags: [...original.tags],
    isDefault: false,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
    createdBy: currentUserEmail || undefined,
  }
  lib.prompts.push(newPrompt)
  try {
    await store.saveLibrary()
    selectedPromptId.value = newPrompt.id
    // Open mobile overlay if on mobile/tablet
    if (isMobile.value || isTablet.value) {
      isMobileDetailOpen.value = true
    }
    startEditing()
  } catch (e) {
    console.error('Failed to duplicate prompt:', e)
    alert('Failed to duplicate prompt. Please try again.')
  }
}

function initiateDeletePrompt(promptId: string) {
  promptToDelete.value = promptId
  deleteDialogOpen.value = true
}

async function confirmDeletePrompt() {
  if (!promptToDelete.value) return

  const promptId = promptToDelete.value
  if (!store.draftLibrary?.prompts) return
  const idx = store.draftLibrary.prompts.findIndex((p) => p.id === promptId)
  if (idx === -1) return

  store.draftLibrary.prompts.splice(idx, 1)
  try {
    await store.saveLibrary()
    if (selectedPromptId.value === promptId) {
      isEditing.value = false
      editingPrompt.value = null
      // Close mobile overlay
      isMobileDetailOpen.value = false
      // Select the first prompt in the list if available
      if (sortedPrompts.value.length > 0) {
        selectedPromptId.value = sortedPrompts.value[0].id
      } else {
        selectedPromptId.value = null
      }
    }
  } catch (e) {
    console.error('Failed to delete prompt:', e)
    alert('Failed to delete prompt. Please try again.')
  } finally {
    deleteDialogOpen.value = false
    promptToDelete.value = null
  }
}

function deletePrompt(promptId: string) {
  initiateDeletePrompt(promptId)
}

function toggleCategoryFilter(category: string) {
  const idx = selectedCategories.value.indexOf(category)
  if (idx === -1) {
    selectedCategories.value.push(category)
  } else {
    selectedCategories.value.splice(idx, 1)
  }
}

function selectAllCategories() {
  // When "Select All" is checked (all individual items are checked), unchecking it should deselect all
  // When "Select All" is unchecked, checking it should select all individual items
  if (
    selectedCategories.value.length === allCategories.value.length &&
    allCategories.value.length > 0
  ) {
    // All are selected, deselect all
    selectedCategories.value = []
  } else {
    // Not all are selected, select all
    selectedCategories.value = [...allCategories.value]
  }
}

function toggleTagFilter(tag: string) {
  const idx = selectedTags.value.indexOf(tag)
  if (idx === -1) {
    selectedTags.value.push(tag)
  } else {
    selectedTags.value.splice(idx, 1)
  }
}

function selectAllTags() {
  // When "Select All" is checked (all individual items are checked), unchecking it should deselect all
  // When "Select All" is unchecked, checking it should select all individual items
  if (selectedTags.value.length === allTags.value.length && allTags.value.length > 0) {
    // All are selected, deselect all
    selectedTags.value = []
  } else {
    // Not all are selected, select all
    selectedTags.value = [...allTags.value]
  }
}

function toggleStatusFilter(status: 'enabled' | 'disabled') {
  const idx = selectedStatus.value.indexOf(status)
  if (idx === -1) {
    selectedStatus.value.push(status)
  } else {
    // Don't allow removing the last status - keep at least one selected
    if (selectedStatus.value.length > 1) {
      selectedStatus.value.splice(idx, 1)
    }
  }
}

const statusFilterLabel = computed(() => {
  if (selectedStatus.value.length === 2) return 'All'
  if (selectedStatus.value.includes('enabled')) return 'Enabled'
  return 'Disabled'
})

function toggleCreatorFilter(creator: string) {
  const idx = selectedCreators.value.indexOf(creator)
  if (idx === -1) {
    selectedCreators.value.push(creator)
  } else {
    selectedCreators.value.splice(idx, 1)
  }
}

function selectAllCreators() {
  // When "Select All" is checked (all individual items are checked), unchecking it should deselect all
  // When "Select All" is unchecked, checking it should select all individual items
  if (selectedCreators.value.length === allCreators.value.length && allCreators.value.length > 0) {
    // All are selected, deselect all
    selectedCreators.value = []
  } else {
    // Not all are selected, select all
    selectedCreators.value = [...allCreators.value]
  }
}

const isEditingWithPrompt = computed(() => isEditing.value && editingPrompt.value !== null)

function updateEditingPromptField(payload: { field: EditablePromptField; value: string }) {
  if (!editingPrompt.value) return
  ;(editingPrompt.value[payload.field] as string) = payload.value
}

function toggleSelectedPromptEnabled() {
  const id = currentPromptId.value
  if (!id) return
  togglePromptEnabled(id)
}

const currentPromptId = computed(() => {
  if (isEditing.value && editingPrompt.value) {
    return editingPrompt.value.id
  }
  return selectedPrompt.value?.id ?? null
})

const currentPromptEnabled = computed(() => {
  const id = currentPromptId.value
  return id ? isPromptEnabled(id) : false
})

// Count enabled prompts among filtered prompts
const enabledPromptsCount = computed(() => {
  return filteredPrompts.value.filter((p) => isPromptEnabled(p.id)).length
})

const allPromptsEnabled = computed(() => {
  if (filteredPrompts.value.length === 0) return false
  return enabledPromptsCount.value === filteredPrompts.value.length
})

function toggleAllPrompts() {
  const shouldEnable = !allPromptsEnabled.value
  filteredPrompts.value.forEach((p) => {
    store.setPromptEnabled(p.id, shouldEnable)
  })
}

type EditablePromptField = 'name' | 'description' | 'category' | 'prompt'

// Auto-select first prompt when prompts are loaded
watch(
  sortedPrompts,
  (newPrompts) => {
    if (newPrompts.length > 0 && !selectedPromptId.value) {
      selectedPromptId.value = newPrompts[0].id
    }
  },
  { immediate: true }
)

onMounted(() => {
  if (!store.loaded) {
    store.load()
  }
})
</script>

<template>
  <div class="max-w-[1600px] mx-auto overflow-hidden h-[calc(100vh-182px)]">
    <div class="flex items-start gap-6 h-full overflow-y-hidden">
      <!-- Prompt List Panel -->
      <div
        :class="selectedPrompt && !isMobile && !isTablet ? 'w-1/2' : 'w-full'"
        class="min-w-0 overflow-x-hidden flex flex-col h-full"
      >
        <div class="flex-shrink-0 space-y-4 pb-4">
          <Input
            v-model="searchQuery"
            placeholder="Search prompts by name, description, prompt, or tags..."
            class="admin-input max-w-[400px]"
          >
            <template #prefix>
              <i class="dku-icon-search-16 admin-icon"></i>
            </template>
          </Input>
          <div class="flex items-center gap-2 overflow-x-auto pb-3 mb-0">
            <DropdownMenu v-model:open="categoriesDropdownOpen">
              <DropdownMenuTrigger asChild>
                <div>
                  <Button variant="outline" class="admin-dropdown-trigger gap-1">
                    <i class="dku-icon-category-16"></i>
                    Categories
                    <span v-if="selectedCategories.length > 0"
                      >({{ selectedCategories.length }})</span
                    >
                    <span v-else>(All)</span>
                    <i
                      class="dku-icon-chevron-down-16 ml-auto transition-transform"
                      :class="{ 'rotate-180': categoriesDropdownOpen }"
                    ></i>
                  </Button>
                </div>
              </DropdownMenuTrigger>
              <DropdownMenuContent
                class="w-56 admin-dropdown-content p-3 max-h-80 overflow-y-auto space-y-2"
              >
                <div
                  v-if="allCategories.length > 0"
                  class="flex items-center gap-2 cursor-pointer hover:bg-muted p-1 rounded"
                  @click="selectAllCategories"
                >
                  <div
                    class="w-4 h-4 border rounded flex items-center justify-center admin-checkbox"
                    :class="{
                      checked:
                        allCategories.length > 0 &&
                        selectedCategories.length === allCategories.length,
                    }"
                  >
                    <i
                      v-if="
                        allCategories.length > 0 &&
                        selectedCategories.length === allCategories.length
                      "
                      class="dku-icon-checkmark-12"
                    ></i>
                  </div>
                  <span class="text-sm">Select All</span>
                </div>
                <div
                  v-for="cat in allCategories"
                  :key="cat"
                  class="flex items-center gap-2 cursor-pointer hover:bg-muted p-1 rounded"
                  @click="toggleCategoryFilter(cat)"
                >
                  <div
                    class="w-4 h-4 border rounded flex items-center justify-center admin-checkbox"
                    :class="{ checked: selectedCategories.includes(cat) }"
                  >
                    <i v-if="selectedCategories.includes(cat)" class="dku-icon-checkmark-12"></i>
                  </div>
                  <span class="text-sm">{{ cat }}</span>
                </div>
                <div v-if="allCategories.length === 0" class="text-xs text-muted-foreground py-2">
                  No categories available
                </div>
              </DropdownMenuContent>
            </DropdownMenu>

            <DropdownMenu v-model:open="tagsDropdownOpen">
              <DropdownMenuTrigger asChild>
                <div>
                  <Button variant="outline" class="admin-dropdown-trigger gap-1">
                    <i class="dku-icon-tag-16"></i>
                    Tags
                    <span v-if="selectedTags.length > 0">({{ selectedTags.length }})</span>
                    <span v-else>(All)</span>
                    <i
                      class="dku-icon-chevron-down-16 ml-auto transition-transform"
                      :class="{ 'rotate-180': tagsDropdownOpen }"
                    ></i>
                  </Button>
                </div>
              </DropdownMenuTrigger>
              <DropdownMenuContent class="w-56 admin-dropdown-content p-3 max-h-80 space-y-2">
                <div
                  v-if="allTags.length > 0"
                  class="flex items-center gap-2 cursor-pointer hover:bg-muted p-1 rounded"
                  @click="selectAllTags"
                >
                  <div
                    class="w-4 h-4 border rounded flex items-center justify-center admin-checkbox"
                    :class="{
                      checked: allTags.length > 0 && selectedTags.length === allTags.length,
                    }"
                  >
                    <i
                      v-if="allTags.length > 0 && selectedTags.length === allTags.length"
                      class="dku-icon-checkmark-12"
                    ></i>
                  </div>
                  <span class="text-sm">Select All</span>
                </div>
                <div
                  v-for="tag in allTags"
                  :key="tag"
                  class="flex items-center gap-2 cursor-pointer hover:bg-muted p-1 rounded"
                  @click="toggleTagFilter(tag)"
                >
                  <div
                    class="w-4 h-4 border rounded flex items-center justify-center admin-checkbox"
                    :class="{ checked: selectedTags.includes(tag) }"
                  >
                    <i v-if="selectedTags.includes(tag)" class="dku-icon-checkmark-12"></i>
                  </div>
                  <span class="text-sm">{{ tag }}</span>
                </div>
                <div v-if="allTags.length === 0" class="text-xs text-muted-foreground py-2">
                  No tags available
                </div>
              </DropdownMenuContent>
            </DropdownMenu>

            <DropdownMenu v-model:open="statusDropdownOpen">
              <DropdownMenuTrigger asChild>
                <div>
                  <Button variant="outline" class="admin-dropdown-trigger gap-1">
                    Status
                    <span>({{ statusFilterLabel }})</span>
                    <i
                      class="dku-icon-chevron-down-16 ml-auto transition-transform"
                      :class="{ 'rotate-180': statusDropdownOpen }"
                    ></i>
                  </Button>
                </div>
              </DropdownMenuTrigger>
              <DropdownMenuContent class="w-48 admin-dropdown-content p-3 space-y-2">
                <div
                  class="flex items-center gap-2 cursor-pointer hover:bg-muted p-1 rounded"
                  @click="toggleStatusFilter('enabled')"
                >
                  <div
                    class="w-4 h-4 border rounded flex items-center justify-center admin-checkbox"
                    :class="{ checked: selectedStatus.includes('enabled') }"
                  >
                    <i v-if="selectedStatus.includes('enabled')" class="dku-icon-checkmark-12"></i>
                  </div>
                  <span class="text-sm">Enabled</span>
                </div>
                <div
                  class="flex items-center gap-2 cursor-pointer hover:bg-muted p-1 rounded"
                  @click="toggleStatusFilter('disabled')"
                >
                  <div
                    class="w-4 h-4 border rounded flex items-center justify-center admin-checkbox"
                    :class="{ checked: selectedStatus.includes('disabled') }"
                  >
                    <i v-if="selectedStatus.includes('disabled')" class="dku-icon-checkmark-12"></i>
                  </div>
                  <span class="text-sm">Disabled</span>
                </div>
              </DropdownMenuContent>
            </DropdownMenu>

            <DropdownMenu v-if="allCreators.length > 0" v-model:open="creatorsDropdownOpen">
              <DropdownMenuTrigger asChild>
                <div>
                  <Button variant="outline" class="admin-dropdown-trigger gap-1">
                    Created by
                    <span v-if="selectedCreators.length > 0">({{ selectedCreators.length }})</span>
                    <i
                      class="dku-icon-chevron-down-16 ml-auto transition-transform"
                      :class="{ 'rotate-180': creatorsDropdownOpen }"
                    ></i>
                  </Button>
                </div>
              </DropdownMenuTrigger>
              <DropdownMenuContent
                class="w-56 admin-dropdown-content p-3 max-h-80 overflow-y-auto space-y-2"
              >
                <div
                  class="flex items-center gap-2 cursor-pointer hover:bg-muted p-1 rounded"
                  @click="selectAllCreators"
                >
                  <div
                    class="w-4 h-4 border rounded flex items-center justify-center admin-checkbox"
                    :class="{
                      checked:
                        allCreators.length > 0 && selectedCreators.length === allCreators.length,
                    }"
                  >
                    <i
                      v-if="
                        allCreators.length > 0 && selectedCreators.length === allCreators.length
                      "
                      class="dku-icon-checkmark-12"
                    ></i>
                  </div>
                  <span class="text-sm">Select All</span>
                </div>
                <div
                  v-for="creator in allCreators"
                  :key="creator"
                  class="flex items-center gap-2 cursor-pointer hover:bg-muted p-1 rounded"
                  @click="toggleCreatorFilter(creator)"
                >
                  <div
                    class="w-4 h-4 border rounded flex items-center justify-center admin-checkbox"
                    :class="{ checked: selectedCreators.includes(creator) }"
                  >
                    <i v-if="selectedCreators.includes(creator)" class="dku-icon-checkmark-12"></i>
                  </div>
                  <span class="text-sm truncate">{{ creator }}</span>
                </div>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>

          <Separator />

          <div class="flex items-center justify-between">
            <span class="text-sm admin-text-muted">
              {{ enabledPromptsCount }} of {{ filteredPrompts.length }} prompts enabled
            </span>
            <div class="flex items-center gap-2">
              <Label class="text-sm cursor-pointer">Enable all</Label>
              <Switch
                :model-value="allPromptsEnabled"
                @update:model-value="toggleAllPrompts"
                class="admin-switch"
              />
            </div>
          </div>
        </div>

        <!-- Scrollable prompts list -->
        <div class="flex-1 overflow-y-auto pr-2 min-h-0">
          <div class="space-y-4">
            <template v-if="!shouldGroupByCategory">
              <div class="grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 gap-3">
                <div
                  class="border-2 border-dashed border-border rounded-lg p-6 cursor-pointer hover:border-foreground/30 hover:bg-foreground/5 transition-colors h-full flex items-center justify-center text-center"
                  @click="createNewPrompt"
                >
                  <div class="flex items-center justify-center">
                    <i class="dku-icon-plus-16 text-xl mr-2"></i>
                    <span class="text font-medium admin-text-primary">Create a New Prompt</span>
                  </div>
                </div>
                <PromptCardAdmin
                  v-for="prompt in filteredPrompts"
                  :key="prompt.id"
                  :prompt="prompt"
                  :selected="selectedPromptId === prompt.id"
                  :enabled="isPromptEnabled(prompt.id)"
                  :search-query="searchQuery"
                  @select="selectPrompt"
                  @toggle-enabled="togglePromptEnabled"
                  @delete="deletePrompt"
                />
              </div>
            </template>

            <template v-else>
              <div class="grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 gap-3">
                <div
                  class="border-2 border-dashed border-border rounded-lg p-6 cursor-pointer hover:border-foreground/30 hover:bg-foreground/5 transition-colors h-full flex items-center justify-center text-center"
                  @click="createNewPrompt"
                >
                  <div class="flex items-center justify-center">
                    <i class="dku-icon-plus-16 text-xl mr-2"></i>
                    <span class="font-medium admin-text-primary">Create a New Prompt</span>
                  </div>
                </div>
              </div>

              <div
                v-for="(prompts, groupName) in groupedPrompts"
                :key="groupName"
                class="space-y-2"
              >
                <Collapsible v-model:open="expandedGroups[groupName]">
                  <CollapsibleTrigger
                    class="flex items-center justify-between w-full py-2 px-3 rounded-lg hover:bg-muted transition-colors"
                  >
                    <div class="flex items-center gap-2">
                      <i
                        class="dku-icon-chevron-up-16 admin-icon transition-transform"
                        :class="{ '-rotate-90': !isGroupExpanded(groupName) }"
                      ></i>
                      <span class="font-semibold text-sm admin-text-primary">{{ groupName }}</span>
                      <Badge variant="secondary" class="text-xs">{{ prompts.length }}</Badge>
                    </div>
                  </CollapsibleTrigger>
                  <CollapsibleContent>
                    <div class="grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 gap-3 mt-2 ml-6">
                      <PromptCardAdmin
                        v-for="prompt in prompts"
                        :key="prompt.id"
                        :prompt="prompt"
                        :selected="selectedPromptId === prompt.id"
                        :enabled="isPromptEnabled(prompt.id)"
                        :search-query="searchQuery"
                        @select="selectPrompt"
                        @toggle-enabled="togglePromptEnabled"
                        @delete="deletePrompt"
                      />
                    </div>
                  </CollapsibleContent>
                </Collapsible>
              </div>
            </template>

            <div v-if="filteredPrompts.length === 0" class="text-center py-12 admin-text-muted">
              <template v-if="libraryPrompts.length === 0">
                <i class="dku-icon-file-text-16 text-4xl mb-3"></i>
                <p class="mb-4">No prompts in the library yet</p>
                <Button size="sm" @click="createNewPrompt" class="admin-btn admin-btn--secondary">
                  <i class="dku-icon-plus-16 mr-1" /> Create your first prompt
                </Button>
              </template>
              <template v-else>
                <i class="dku-icon-search-16 text-4xl mb-3"></i>
                <p>No prompts found matching your filters</p>
              </template>
            </div>
          </div>
        </div>
      </div>

      <!-- Desktop: Side-by-side detail panel -->
      <SelectedPromptCardAdmin
        v-if="selectedPrompt && !isMobile && !isTablet"
        :selected-prompt="selectedPrompt"
        :is-editing="isEditing"
        :editing-prompt="editingPrompt"
        :is-editing-with-prompt="isEditingWithPrompt"
        v-model:tags-input="tagsInput"
        :is-current-prompt-enabled="currentPromptEnabled"
        :search-query="searchQuery"
        :all-categories="allCategories"
        :all-tags="allTags"
        @delete="deletePrompt"
        @duplicate="duplicatePrompt"
        @start-editing="startEditing"
        @cancel-editing="cancelEditing"
        @save="savePrompt"
        @toggle-enabled="toggleSelectedPromptEnabled"
        @updateEditingPromptField="updateEditingPromptField"
      />
    </div>

    <!-- Mobile/Tablet: Full-screen overlay for prompt detail -->
    <Transition name="mobile-detail-slide">
      <div
        v-if="(isMobile || isTablet) && isMobileDetailOpen && selectedPrompt"
        class="fixed inset-0 z-50 bg-white flex flex-col"
      >
        <!-- Header with back button -->
        <div class="flex items-center justify-between p-4 border-b shrink-0">
          <div class="flex items-center space-x-3">
            <Button variant="ghost" size="sm" @click="closeMobileDetail" class="shrink-0">
              <i class="dku-icon-chevron-left-16"></i>
              Back to Prompt Library
            </Button>
          </div>
        </div>

        <!-- Content -->
        <div class="overflow-y-auto flex-1 p-4">
          <SelectedPromptCardAdmin
            :selected-prompt="selectedPrompt"
            :is-editing="isEditing"
            :editing-prompt="editingPrompt"
            :is-editing-with-prompt="isEditingWithPrompt"
            v-model:tags-input="tagsInput"
            :is-current-prompt-enabled="currentPromptEnabled"
            :search-query="searchQuery"
            :all-categories="allCategories"
            :all-tags="allTags"
            :is-mobile="true"
            @delete="deletePrompt"
            @duplicate="duplicatePrompt"
            @start-editing="startEditing"
            @cancel-editing="cancelEditing"
            @save="savePrompt"
            @toggle-enabled="toggleSelectedPromptEnabled"
            @updateEditingPromptField="updateEditingPromptField"
          />
        </div>
      </div>
    </Transition>

    <AlertDialog v-model:open="deleteDialogOpen">
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle> <i class="dku-icon-trash-16 mr-2"></i>Delete Prompt </AlertDialogTitle>
          <AlertDialogDescription>
            This action cannot be undone. This prompt will be permanently removed from the library.
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel>Cancel</AlertDialogCancel>
          <AlertDialogAction
            @click="confirmDeletePrompt"
            class="bg-red-600 text-white hover:bg-red-700"
          >
            Delete the prompt
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  </div>
</template>

<style scoped>
.mobile-detail-slide-enter-active,
.mobile-detail-slide-leave-active {
  transition: all 0.3s ease;
}

.mobile-detail-slide-enter-from {
  opacity: 0;
  transform: translateX(100%);
}

.mobile-detail-slide-leave-to {
  opacity: 0;
  transform: translateX(100%);
}
</style>
