<script setup lang="ts">
import type { Prompt } from '@/types/admin-config'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Separator } from '@/components/ui/separator'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { highlightText } from '@/lib/utils'
import { computed, ref } from 'vue'

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

const props = defineProps<{
  selectedPrompt: Prompt | null
  isEditing: boolean
  editingPrompt: Prompt | null
  isEditingWithPrompt: boolean
  tagsInput: string
  isCurrentPromptEnabled: boolean
  searchQuery?: string
  allCategories: string[]
  allTags: string[]
  isMobile?: boolean
}>()

const emit = defineEmits<{
  (e: 'delete', id: string): void
  (e: 'duplicate'): void
  (e: 'start-editing'): void
  (e: 'cancel-editing'): void
  (e: 'save'): void
  (e: 'toggle-enabled'): void
  (e: 'update:tagsInput', value: string): void
  (e: 'updateEditingPromptField', payload: { field: EditablePromptField; value: string }): void
}>()

const hasSelectedPrompt = computed(() => props.selectedPrompt !== null)

const MAX_VISIBLE_TAGS = 3

const visibleTags = computed(() => {
  const tags = props.selectedPrompt?.tags || []
  return tags.length > MAX_VISIBLE_TAGS ? tags.slice(0, MAX_VISIBLE_TAGS) : tags
})

const remainingTags = computed(() => {
  const tags = props.selectedPrompt?.tags || []
  return tags.length > MAX_VISIBLE_TAGS ? tags.slice(MAX_VISIBLE_TAGS) : []
})

const remainingTagsCount = computed(() => remainingTags.value.length)

// Highlighted text computations
const highlightedName = computed(() =>
  highlightText(props.selectedPrompt?.name || '', props.searchQuery || '')
)

const highlightedDescription = computed(() =>
  highlightText(props.selectedPrompt?.description || 'No description', props.searchQuery || '')
)

const highlightedPromptContent = computed(() =>
  highlightText(props.selectedPrompt?.prompt || '', props.searchQuery || '')
)

const getHighlightedTag = (tag: string) => highlightText(tag, props.searchQuery || '')

const copied = ref(false)

async function copyPromptContent() {
  if (!props.selectedPrompt?.prompt) return
  try {
    await navigator.clipboard.writeText(props.selectedPrompt.prompt)
    copied.value = true
    setTimeout(() => {
      copied.value = false
    }, 2000)
  } catch (err) {
    console.error('Failed to copy:', err)
  }
}

function handleDelete() {
  if (!props.selectedPrompt) return
  emit('delete', props.selectedPrompt.id)
}

function handleDuplicate() {
  emit('duplicate')
}

function handleStartEditing() {
  emit('start-editing')
}

function handleCancelEditing() {
  emit('cancel-editing')
}

function handleSave() {
  emit('save')
}

function handleEditingPromptFieldUpdate(field: EditablePromptField, value: string | number) {
  emit('updateEditingPromptField', { field, value: String(value) })
}

// Category select logic
const categoryDropdownOpen = ref(false)
const newCategoryInput = ref('')

const currentTags = computed(() => {
  if (!props.editingPrompt) return []
  return props.editingPrompt.tags || []
})

function selectCategory(category: string) {
  handleEditingPromptFieldUpdate('category', category)
  categoryDropdownOpen.value = false
}

function addNewCategory() {
  const trimmed = newCategoryInput.value.trim()
  if (trimmed) {
    handleEditingPromptFieldUpdate('category', trimmed)
    newCategoryInput.value = ''
    categoryDropdownOpen.value = false
  }
}

function handleNewCategoryKeydown(event: KeyboardEvent) {
  if (event.key === 'Enter') {
    event.preventDefault()
    addNewCategory()
  }
}

// Tags select logic
const tagsDropdownOpen = ref(false)
const newTagInput = ref('')

function toggleTag(tag: string) {
  const tags = [...currentTags.value]
  const idx = tags.indexOf(tag)
  if (idx === -1) {
    tags.push(tag)
  } else {
    tags.splice(idx, 1)
  }
  emit('update:tagsInput', tags.join(', '))
}

function isTagSelected(tag: string): boolean {
  return currentTags.value.includes(tag)
}

function addNewTag() {
  const trimmed = newTagInput.value.trim()
  if (trimmed && !currentTags.value.includes(trimmed)) {
    const tags = [...currentTags.value, trimmed]
    emit('update:tagsInput', tags.join(', '))
    newTagInput.value = ''
  }
}

function handleNewTagKeydown(event: KeyboardEvent) {
  if (event.key === 'Enter') {
    event.preventDefault()
    addNewTag()
  }
}

function selectAllTags() {
  // If all are already selected, deselect all by clearing tags
  // Otherwise, select all tags
  if (currentTags.value.length === props.allTags.length && props.allTags.length > 0) {
    emit('update:tagsInput', '')
  } else {
    emit('update:tagsInput', props.allTags.join(', '))
  }
}

const tagsDisplayLabel = computed(() => {
  const count = currentTags.value.length
  if (count === 0) return 'Select tags'
  return `${count} Tag${count > 1 ? 's' : ''}`
})
</script>

<template>
  <div
    v-if="hasSelectedPrompt && selectedPrompt"
    :class="[
      'min-w-0 overflow-x-hidden admin-card p-6 flex flex-col h-full',
      isMobile ? 'w-full' : 'w-1/2',
    ]"
  >
    <!-- View Mode -->
    <template v-if="!isEditing">
      <div class="flex-shrink-0">
        <!-- Header: Title + Action buttons -->
        <div class="flex items-start justify-between gap-4">
          <h3 class="text-xl font-semibold admin-text-primary">
            <template v-for="(part, idx) in highlightedName" :key="idx">
              <mark v-if="part.highlighted" class="search-highlight">{{ part.text }}</mark>
              <template v-else>{{ part.text }}</template>
            </template>
          </h3>
          <div class="flex gap-2 flex-shrink-0">
            <Tooltip v-if="!selectedPrompt.isDefault">
              <TooltipTrigger asChild>
                <Button
                  @click="handleDuplicate"
                  variant="outline"
                  size="sm"
                  class="admin-btn admin-btn--secondary"
                >
                  <i class="dku-icon-copy-16"></i>
                </Button>
              </TooltipTrigger>
              <TooltipContent hide-arrow>Duplicate</TooltipContent>
            </Tooltip>
            <Tooltip v-if="!selectedPrompt.isDefault">
              <TooltipTrigger asChild>
                <Button
                  @click="handleStartEditing"
                  variant="outline"
                  size="sm"
                  class="admin-btn admin-btn--secondary"
                >
                  <i class="dku-icon-edit-16"></i>
                </Button>
              </TooltipTrigger>
              <TooltipContent hide-arrow>Edit</TooltipContent>
            </Tooltip>
            <Tooltip v-if="!selectedPrompt.isDefault">
              <TooltipTrigger asChild>
                <Button
                  @click="handleDelete"
                  variant="outline"
                  size="sm"
                  class="admin-btn admin-btn-destructive"
                >
                  <i class="dku-icon-trash-16"></i>
                </Button>
              </TooltipTrigger>
              <TooltipContent hide-arrow>Delete</TooltipContent>
            </Tooltip>
            <Button
              v-if="selectedPrompt.isDefault"
              @click="handleDuplicate"
              variant="outline"
              size="sm"
              class="admin-btn admin-btn--secondary"
            >
              <i class="dku-icon-copy-16 mr-1"></i>
              Duplicate
            </Button>
          </div>
        </div>
        <!-- Description -->
        <p class="text-sm admin-text-muted mt-2">
          <template v-for="(part, idx) in highlightedDescription" :key="idx">
            <mark v-if="part.highlighted" class="search-highlight">{{ part.text }}</mark>
            <template v-else>{{ part.text }}</template>
          </template>
        </p>

        <!-- Metadata row: Created by, Category, Tags -->
        <div class="flex items-start gap-6 mt-4 pb-4 overflow-x-auto">
          <div>
            <Label class="admin-field-label text-xs">Created by</Label>
            <div class="flex items-center gap-1.5 mt-1">
              <i
                class="admin-section-icon text-base"
                :class="selectedPrompt.isDefault ? 'dku-icon-dataiku-16' : 'dku-icon-user-16'"
              ></i>
              <span class="text-sm admin-text-primary">
                {{ selectedPrompt.isDefault ? 'Dataiku' : selectedPrompt.createdBy || 'User' }}
              </span>
            </div>
          </div>

          <div>
            <Label class="admin-field-label text-xs">Category</Label>
            <p class="text-sm admin-text-primary mt-1">{{ selectedPrompt.category }}</p>
          </div>

          <div class="flex-1" v-if="visibleTags.length > 0">
            <Label class="admin-field-label text-xs">Tags</Label>
            <div class="flex items-center gap-1.5 mt-1 flex-wrap">
              <template v-if="selectedPrompt.tags && selectedPrompt.tags.length > 0">
                <span
                  v-for="tag in visibleTags"
                  :key="tag"
                  class="text-xs px-2 py-0.5 rounded-md bg-muted text-muted-foreground truncate max-w-[80px]"
                >
                  <template v-for="(part, partIdx) in getHighlightedTag(tag)" :key="partIdx">
                    <mark v-if="part.highlighted" class="search-highlight">{{ part.text }}</mark>
                    <template v-else>{{ part.text }}</template>
                  </template>
                </span>
                <Tooltip v-if="remainingTagsCount > 0">
                  <TooltipTrigger asChild>
                    <span
                      class="text-xs px-2 py-0.5 rounded-md bg-muted text-muted-foreground cursor-default"
                    >
                      +{{ remainingTagsCount }}
                    </span>
                  </TooltipTrigger>
                  <TooltipContent hide-arrow>
                    <div class="flex flex-col gap-1">
                      <span v-for="tag in remainingTags" :key="tag">{{ tag }}</span>
                    </div>
                  </TooltipContent>
                </Tooltip>
              </template>
            </div>
          </div>
        </div>

        <Separator class="mb-4" />

        <div class="flex items-center justify-between mb-2">
          <Label class="admin-field-label">Prompt Content</Label>
          <Tooltip>
            <TooltipTrigger asChild>
              <button
                @click="copyPromptContent"
                class="p-1.5 rounded-md hover:bg-muted transition-colors admin-text-muted hover:admin-text-primary mr-3"
              >
                <i :class="copied ? 'dku-icon-checkmark-16' : 'dku-icon-copy-step-16'"></i>
              </button>
            </TooltipTrigger>
            <TooltipContent hide-arrow>{{ copied ? 'Copied!' : 'Copy Prompt' }}</TooltipContent>
          </Tooltip>
        </div>
      </div>

      <div class="flex-1 overflow-y-auto min-h-0">
        <div class="px-4 my-4 border-l-2 border-border">
          <div class="text-sm whitespace-pre-wrap admin-text-primary">
            <template v-for="(part, idx) in highlightedPromptContent" :key="idx"
              ><mark v-if="part.highlighted" class="search-highlight">{{ part.text }}</mark
              ><template v-else>{{ part.text }}</template></template
            >
          </div>
        </div>
      </div>
    </template>

    <!-- Edit Mode -->
    <template v-else-if="isEditingWithPrompt && editingPrompt">
      <!-- Header: Name input + Delete button -->
      <div class="flex-shrink-0">
        <div class="flex items-center justify-between gap-4 mb-4">
          <div class="space-y-2">
            <Label class="admin-field-label">Name</Label>
            <Input
              :model-value="editingPrompt.name"
              class="admin-input max-w-[300px]"
              @update:model-value="(value) => handleEditingPromptFieldUpdate('name', value)"
            />
          </div>
          <Tooltip>
            <TooltipTrigger asChild>
              <Button
                @click="handleDelete"
                variant="outline"
                size="sm"
                class="admin-btn admin-btn-destructive flex-shrink-0"
              >
                <i class="dku-icon-trash-16"></i>
              </Button>
            </TooltipTrigger>
            <TooltipContent hide-arrow>Delete</TooltipContent>
          </Tooltip>
        </div>
      </div>

      <!-- Form fields -->
      <div class="flex-1 flex flex-col overflow-y-auto space-y-4 min-h-0">
        <div class="space-y-2">
          <Label class="admin-field-label">Description</Label>
          <Textarea
            :model-value="editingPrompt.description"
            rows="3"
            class="w-full !border !border-border rounded-md shadow-sm admin-textarea text-sm py-2 px-3 resize-y placeholder-muted-foreground"
            @update:model-value="(value) => handleEditingPromptFieldUpdate('description', value)"
          />
        </div>

        <div class="space-y-2">
          <Label class="admin-field-label">Category</Label>
          <Popover v-model:open="categoryDropdownOpen">
            <PopoverTrigger as-child>
              <Button variant="outline" class="admin-dropdown-trigger gap-1">
                <i class="dku-icon-category-16"></i>
                <span :class="editingPrompt.category ? '' : 'text-muted-foreground'">
                  {{ editingPrompt.category || 'Select category...' }}
                </span>
                <i
                  class="dku-icon-chevron-down-16 ml-auto transition-transform"
                  :class="{ 'rotate-180': categoryDropdownOpen }"
                ></i>
              </Button>
            </PopoverTrigger>
            <PopoverContent class="w-56 admin-dropdown-content p-0" align="start">
              <div class="max-h-60 overflow-y-auto p-2 space-y-1">
                <div
                  v-for="cat in allCategories"
                  :key="cat"
                  class="flex items-center gap-2 cursor-pointer hover:bg-muted p-2 rounded text-sm"
                  @click="selectCategory(cat)"
                >
                  <div
                    class="w-4 h-4 border rounded flex items-center justify-center admin-checkbox"
                    :class="{ checked: editingPrompt.category === cat }"
                  >
                    <i v-if="editingPrompt.category === cat" class="dku-icon-checkmark-12"></i>
                  </div>
                  <span>{{ cat }}</span>
                </div>
                <div
                  v-if="allCategories.length === 0"
                  class="text-xs text-muted-foreground py-2 px-2"
                >
                  No categories available
                </div>
              </div>
              <div class="border-t p-2">
                <Input
                  v-model="newCategoryInput"
                  class="admin-input text-sm"
                  placeholder="+ Add Category"
                  @keydown="handleNewCategoryKeydown"
                />
              </div>
            </PopoverContent>
          </Popover>
        </div>

        <div class="space-y-2">
          <Label class="admin-field-label">Tags</Label>
          <Popover v-model:open="tagsDropdownOpen">
            <PopoverTrigger as-child>
              <Button variant="outline" class="admin-dropdown-trigger gap-1">
                <i class="dku-icon-tag-16"></i>
                <span :class="currentTags.length > 0 ? '' : 'text-muted-foreground'">
                  {{ tagsDisplayLabel }}
                </span>
                <i
                  class="dku-icon-chevron-down-16 ml-auto transition-transform"
                  :class="{ 'rotate-180': tagsDropdownOpen }"
                ></i>
              </Button>
            </PopoverTrigger>
            <PopoverContent class="w-56 admin-dropdown-content p-0" align="start">
              <div class="max-h-60 overflow-y-auto p-2 space-y-1">
                <div
                  class="flex items-center gap-2 cursor-pointer hover:bg-muted p-2 rounded text-sm"
                  @click="selectAllTags"
                >
                  <div
                    class="w-4 h-4 border rounded flex items-center justify-center admin-checkbox"
                    :class="{
                      checked: currentTags.length === allTags.length && allTags.length > 0,
                    }"
                  >
                    <i
                      v-if="currentTags.length === allTags.length && allTags.length > 0"
                      class="dku-icon-checkmark-12"
                    ></i>
                  </div>
                  <span>Select All</span>
                </div>
                <div
                  v-for="tag in allTags"
                  :key="tag"
                  class="flex items-center gap-2 cursor-pointer hover:bg-muted p-2 rounded text-sm"
                  @click="toggleTag(tag)"
                >
                  <div
                    class="w-4 h-4 border rounded flex items-center justify-center admin-checkbox"
                    :class="{ checked: isTagSelected(tag) }"
                  >
                    <i v-if="isTagSelected(tag)" class="dku-icon-checkmark-12"></i>
                  </div>
                  <span>{{ tag }}</span>
                </div>
                <div v-if="allTags.length === 0" class="text-xs text-muted-foreground py-2 px-2">
                  No tags available
                </div>
              </div>
              <div class="border-t p-2">
                <Input
                  v-model="newTagInput"
                  class="admin-input text-sm"
                  placeholder="+ Add New Tag"
                  @keydown="handleNewTagKeydown"
                />
              </div>
            </PopoverContent>
          </Popover>
        </div>

        <div class="flex flex-col space-y-2 flex-1">
          <Label class="admin-field-label">Prompt Content</Label>
          <Textarea
            :model-value="editingPrompt.prompt"
            class="w-full h-full !border !border-border rounded-md shadow-sm admin-textarea text-sm py-2 px-3 resize-y placeholder-muted-foreground"
            @update:model-value="(value) => handleEditingPromptFieldUpdate('prompt', value)"
          />
        </div>
      </div>

      <!-- Footer: Cancel + Save buttons -->
      <div class="flex-shrink-0 border-t pt-4 mt-4">
        <div class="flex justify-end gap-2">
          <Button
            @click="handleCancelEditing"
            variant="outline"
            size="sm"
            class="admin-btn admin-btn--secondary"
          >
            Cancel
          </Button>
          <Button @click="handleSave" size="sm" class="admin-btn admin-btn--primary">
            <i class="dku-icon-save-16 mr-1"></i>
            Save
          </Button>
        </div>
      </div>
    </template>
  </div>
</template>
