<script setup lang="ts">
import { ref, computed } from 'vue'
import { storeToRefs } from 'pinia'
import { useI18n } from 'vue-i18n'
import { useSemanticModelsStore } from '@/stores/semantic-models'
import { toast } from 'vue-sonner'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import ConfirmDialog from '@/components/ConfirmDialog.vue'
import AddTermsManuallyModal from '@/components/editor/AddTermsManuallyModal.vue'
import AddTermsFromDocumentModal from '@/components/editor/AddTermsFromDocumentModal.vue'
import type { GlossaryTerm, GlossaryTermUpdate } from '@/types'

const props = defineProps<{
  modelId: string
  versionId: string
}>()

const semanticModelsStore = useSemanticModelsStore()
const { draftGlossaryTerms } = storeToRefs(semanticModelsStore)
const { t } = useI18n()

// UI State
const searchQuery = ref('')
const showManualModal = ref(false)
const showDocumentModal = ref(false)
const editingTermId = ref<string | null>(null)
const showDeleteDialog = ref(false)
const termToDelete = ref<GlossaryTerm | null>(null)
const showDeleteAllDialog = ref(false)
const showBulkDeleteDialog = ref(false)

// Multi-select state
const selectedTermIds = ref<Set<string>>(new Set())

// Edit form
const editForm = ref<GlossaryTermUpdate>({})
const editSynonymsText = ref('')

// Computed
const filteredTerms = computed(() => {
  // Sort alphabetically by term name
  let terms = [...draftGlossaryTerms.value].sort((a, b) =>
    a.term.localeCompare(b.term, undefined, { sensitivity: 'base' })
  )

  // Search filter
  if (searchQuery.value.trim()) {
    const query = searchQuery.value.toLowerCase()
    terms = terms.filter(
      (t) =>
        t.term.toLowerCase().includes(query) ||
        t.description?.toLowerCase().includes(query) ||
        t.synonyms?.some((s) => s.toLowerCase().includes(query))
    )
  }

  return terms
})

// Multi-select computed
const selectedCount = computed(() => selectedTermIds.value.size)
const hasSelection = computed(() => selectedCount.value > 0)
const allSelected = computed(() =>
  filteredTerms.value.length > 0 && filteredTerms.value.every(t => selectedTermIds.value.has(t.id))
)
const someSelected = computed(() =>
  selectedTermIds.value.size > 0 && !allSelected.value
)

function isTermSelected(termId: string): boolean {
  return selectedTermIds.value.has(termId)
}

function toggleTermSelection(termId: string) {
  if (selectedTermIds.value.has(termId)) {
    selectedTermIds.value.delete(termId)
  } else {
    selectedTermIds.value.add(termId)
  }
  // Trigger reactivity
  selectedTermIds.value = new Set(selectedTermIds.value)
}

function toggleSelectAll() {
  if (allSelected.value) {
    selectedTermIds.value = new Set()
  } else {
    selectedTermIds.value = new Set(filteredTerms.value.map(t => t.id))
  }
}

function clearSelection() {
  selectedTermIds.value = new Set()
}

function handleBulkDelete() {
  if (selectedCount.value === 0) return
  showBulkDeleteDialog.value = true
}

function confirmBulkDelete() {
  draftGlossaryTerms.value = draftGlossaryTerms.value.filter(
    (t) => !selectedTermIds.value.has(t.id)
  )
  toast.success(t('terms.deleted', selectedCount.value))
  clearSelection()
  showBulkDeleteDialog.value = false
}

// Actions
function handleAddTerms(terms: GlossaryTerm[]) {
  // Add terms to the beginning of the list (newest first)
  for (const term of terms) {
    draftGlossaryTerms.value.unshift(term)
  }
  if (terms.length > 0) {
    toast.success(t('terms.added', terms.length))
  }
}

function startEdit(term: GlossaryTerm) {
  editingTermId.value = term.id
  editForm.value = {
    term: term.term,
    description: term.description || '',
    synonyms: term.synonyms || [],
  }
  editSynonymsText.value = (term.synonyms || []).join(', ')
}

function cancelEdit() {
  editingTermId.value = null
  editForm.value = {}
  editSynonymsText.value = ''
}

async function saveEdit(termId: string) {
  // Validate term name is not empty
  if (!editForm.value.term?.trim()) {
    toast.error('Term name cannot be empty')
    return
  }

  try {
    const data: GlossaryTermUpdate = {
      term: editForm.value.term.trim(),
      description: editForm.value.description?.trim() || undefined,
      synonyms: editSynonymsText.value
        ? editSynonymsText.value.split(',').map((s) => s.trim()).filter(Boolean)
        : [],
    }

    const now = new Date().toISOString()
    const index = draftGlossaryTerms.value.findIndex((t) => t.id === termId)
    if (index === -1) {
      toast.error('Term not found')
      return
    }
    const current = draftGlossaryTerms.value[index]
    draftGlossaryTerms.value[index] = {
      ...current,
      term: data.term ?? current.term,
      description: data.description,
      synonyms: data.synonyms ?? current.synonyms,
      userModified: true,
      modified: { on: now },
    }
    toast.success('Term updated')
    cancelEdit()
  } catch (e) {
    toast.error(e instanceof Error ? e.message : 'Failed to update term')
  }
}

function openDeleteDialog(term: GlossaryTerm) {
  termToDelete.value = term
  showDeleteDialog.value = true
}

function handleConfirmDelete() {
  if (!termToDelete.value) return

  try {
    draftGlossaryTerms.value = draftGlossaryTerms.value.filter((t) => t.id !== termToDelete.value!.id)
    toast.success('Term deleted')
  } catch (e) {
    toast.error(e instanceof Error ? e.message : 'Failed to delete term')
  } finally {
    termToDelete.value = null
  }
}

function handleConfirmDeleteAll() {
  draftGlossaryTerms.value = []
  toast.success('All terms deleted')
}
</script>

<template>
  <div class="flex h-full flex-col">
    <!-- Sticky Header with search and actions -->
    <div class="sticky top-0 z-10 bg-background pb-4">
      <div class="flex items-center justify-between gap-4">
        <div class="flex items-center gap-4">
          <!-- Search -->
          <div class="relative">
            <i class="dku-icon-search-16 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />
            <input
              v-model="searchQuery"
              type="text"
              placeholder="Search terms..."
              class="h-9 w-64 rounded-md border bg-background pl-9 pr-3 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
            />
          </div>
        </div>

        <div class="flex items-center gap-2">
          <button
            v-if="draftGlossaryTerms.length > 0"
            class="btn-delete"
            @click="showDeleteAllDialog = true"
          >
            Delete All
          </button>
          <DropdownMenu>
            <DropdownMenuTrigger as-child>
              <button class="btn-tertiary">
                + Add Terms
              </button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuItem @click="showManualModal = true">
                <i class="dku-icon-edit-16 mr-2" />
                Add Manually
              </DropdownMenuItem>
              <DropdownMenuItem @click="showDocumentModal = true">
                <i class="dku-icon-stars-16 mr-2" />
                Extract from Document
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </div>
    </div>

    <!-- Terms Table -->
    <div class="flex flex-1 flex-col overflow-hidden rounded-lg border">
      <!-- Bulk action bar when items selected -->
      <div
        v-if="hasSelection"
        class="flex shrink-0 items-center gap-3 bg-primary/10 px-3 py-2 border-b"
      >
        <input
          type="checkbox"
          class="h-4 w-4 rounded border-input"
          :checked="allSelected"
          :indeterminate="someSelected"
          @change="toggleSelectAll"
        />
        <span class="text-sm font-medium">{{ selectedCount }} selected</span>
        <button
          class="text-sm font-medium text-destructive hover:underline"
          @click="handleBulkDelete"
        >
          DELETE SELECTED
        </button>
      </div>

      <!-- Fixed Header -->
      <Table v-if="!hasSelection" class="w-full shrink-0 table-fixed">
        <colgroup>
          <col class="w-10" />
          <col class="w-[17%]" />
          <col class="w-[31%]" />
          <col class="w-[24%]" />
          <col class="w-[10%]" />
          <col class="w-[14%]" />
        </colgroup>
        <TableHeader class="bg-background">
          <TableRow>
            <TableHead class="w-10">
              <input
                type="checkbox"
                class="h-4 w-4 rounded border-input"
                :checked="allSelected"
                :indeterminate="someSelected"
                @change="toggleSelectAll"
              />
            </TableHead>
            <TableHead>Term</TableHead>
            <TableHead>Description</TableHead>
            <TableHead>Synonyms</TableHead>
            <TableHead>Source</TableHead>
            <TableHead class="text-right">Actions</TableHead>
          </TableRow>
        </TableHeader>
      </Table>

      <!-- Scrollable Body -->
      <div class="flex-1 overflow-y-auto overflow-x-hidden">
        <Table class="w-full table-fixed">
          <colgroup>
            <col class="w-10" />
            <col class="w-[17%]" />
            <col class="w-[31%]" />
            <col class="w-[24%]" />
            <col class="w-[10%]" />
            <col class="w-[14%]" />
          </colgroup>
          <TableBody>
          <TableRow
            v-for="term in filteredTerms"
            :key="term.id"
            class="group"
            :class="{ 'bg-primary/5': isTermSelected(term.id) }"
          >
            <!-- Checkbox column -->
            <TableCell class="w-10 p-2">
              <input
                type="checkbox"
                class="h-4 w-4 rounded border-input"
                :checked="isTermSelected(term.id)"
                @change="toggleTermSelection(term.id)"
              />
            </TableCell>

            <!-- Editing mode -->
            <template v-if="editingTermId === term.id">
              <TableCell class="overflow-hidden p-2">
                <input
                  v-model="editForm.term"
                  type="text"
                  class="h-8 w-full rounded border bg-background px-2 text-sm"
                  @keydown.enter="saveEdit(term.id)"
                />
              </TableCell>
              <TableCell class="overflow-hidden p-2">
                <textarea
                  v-model="editForm.description"
                  rows="2"
                  class="w-full rounded border bg-background px-2 py-1 text-sm"
                />
              </TableCell>
              <TableCell class="overflow-hidden p-2">
                <input
                  v-model="editSynonymsText"
                  type="text"
                  class="h-8 w-full rounded border bg-background px-2 text-sm"
                  placeholder="Comma-separated"
                  @keydown.enter="saveEdit(term.id)"
                />
              </TableCell>
              <TableCell class="overflow-hidden p-2 text-sm text-muted-foreground">
                <span class="block truncate">{{ term.source }}</span>
              </TableCell>
              <TableCell class="p-2 text-right">
                <div class="flex items-center justify-end gap-1">
                  <Tooltip>
                    <TooltipTrigger as-child>
                      <button
                        class="rounded p-1.5 text-green-600 hover:bg-green-100 dark:hover:bg-green-900/30"
                        @click="saveEdit(term.id)"
                      >
                        <i class="dku-icon-checkmark-12" />
                      </button>
                    </TooltipTrigger>
                    <TooltipContent>Save</TooltipContent>
                  </Tooltip>
                  <Tooltip>
                    <TooltipTrigger as-child>
                      <button
                        class="rounded p-1.5 text-muted-foreground hover:bg-muted"
                        @click="cancelEdit"
                      >
                        <i class="dku-icon-dismiss-12" />
                      </button>
                    </TooltipTrigger>
                    <TooltipContent>Cancel</TooltipContent>
                  </Tooltip>
                </div>
              </TableCell>
            </template>

            <!-- Display mode -->
            <template v-else>
              <TableCell class="overflow-hidden p-2">
                <div class="flex items-center truncate">
                  <Tooltip>
                    <TooltipTrigger as-child>
                      <span class="truncate font-medium">{{ term.term }}</span>
                    </TooltipTrigger>
                    <TooltipContent class="max-w-sm">{{ term.term }}</TooltipContent>
                  </Tooltip>
                  <Tooltip v-if="term.userModified">
                    <TooltipTrigger as-child>
                      <span class="ml-2 shrink-0 text-xs text-muted-foreground">
                        (edited)
                      </span>
                    </TooltipTrigger>
                    <TooltipContent>Manually edited</TooltipContent>
                  </Tooltip>
                </div>
              </TableCell>
              <TableCell class="overflow-hidden p-2 text-sm text-muted-foreground">
                <Tooltip>
                  <TooltipTrigger as-child>
                    <span class="block truncate">{{ term.description || '-' }}</span>
                  </TooltipTrigger>
                  <TooltipContent class="max-w-sm">{{ term.description || '-' }}</TooltipContent>
                </Tooltip>
              </TableCell>
              <TableCell class="overflow-hidden p-2 text-sm text-muted-foreground">
                <Tooltip>
                  <TooltipTrigger as-child>
                    <span class="block truncate">
                      {{ term.synonyms?.length ? term.synonyms.join(', ') : '-' }}
                    </span>
                  </TooltipTrigger>
                  <TooltipContent class="max-w-sm">
                    {{ term.synonyms?.length ? term.synonyms.join(', ') : '-' }}
                  </TooltipContent>
                </Tooltip>
              </TableCell>
              <TableCell class="overflow-hidden p-2 text-sm text-muted-foreground">
                <span class="block truncate">{{ term.source }}</span>
              </TableCell>
              <TableCell class="p-2 text-right">
                <div class="flex items-center justify-end gap-1 opacity-0 transition-opacity group-hover:opacity-100">
                  <!-- Edit -->
                  <Tooltip>
                    <TooltipTrigger as-child>
                      <button
                        class="rounded p-1.5 text-muted-foreground hover:bg-muted"
                        @click="startEdit(term)"
                      >
                        <i class="dku-icon-edit-16" />
                      </button>
                    </TooltipTrigger>
                    <TooltipContent>Edit</TooltipContent>
                  </Tooltip>
                  <!-- Delete -->
                  <Tooltip>
                    <TooltipTrigger as-child>
                      <button
                        class="rounded p-1.5 text-destructive hover:bg-destructive/10"
                        @click="openDeleteDialog(term)"
                      >
                        <i class="dku-icon-trash-16" />
                      </button>
                    </TooltipTrigger>
                    <TooltipContent>Delete</TooltipContent>
                  </Tooltip>
                </div>
              </TableCell>
            </template>
          </TableRow>

          <!-- Empty state -->
          <TableRow v-if="filteredTerms.length === 0">
            <TableCell colspan="5" class="px-4 py-8 text-center text-muted-foreground">
              <template v-if="searchQuery">
                No terms match your filters
              </template>
              <template v-else>
                No glossary terms yet. Add terms manually or extract from documents.
              </template>
            </TableCell>
          </TableRow>
        </TableBody>
        </Table>
      </div>
    </div>

    <!-- Add Terms Manually Modal -->
    <AddTermsManuallyModal
      :show="showManualModal"
      :existing-terms="draftGlossaryTerms"
      @close="showManualModal = false"
      @add-terms="handleAddTerms"
    />

    <!-- Add Terms from Document Modal -->
    <AddTermsFromDocumentModal
      :show="showDocumentModal"
      :model-id="props.modelId"
      :version-id="props.versionId"
      @close="showDocumentModal = false"
    />

    <!-- Delete Confirmation Dialog -->
    <ConfirmDialog
      v-model:open="showDeleteDialog"
      title="Delete Term"
      :description="`Are you sure you want to delete '${termToDelete?.term}'? Click Save to persist this change.`"
      confirm-text="Delete"
      cancel-text="Cancel"
      variant="destructive"
      @confirm="handleConfirmDelete"
    />

    <!-- Delete All Confirmation Dialog -->
    <ConfirmDialog
      v-model:open="showDeleteAllDialog"
      title="Delete All Terms"
      :description="`Are you sure you want to delete all ${t('terms.count', draftGlossaryTerms.length)}? Click Save to persist this change.`"
      confirm-text="Delete All"
      cancel-text="Cancel"
      variant="destructive"
      @confirm="handleConfirmDeleteAll"
    />

    <!-- Bulk Delete Dialog -->
    <ConfirmDialog
      v-model:open="showBulkDeleteDialog"
      title="Delete Terms"
      :description="`Are you sure you want to delete ${t('terms.count', selectedCount)}?`"
      confirm-text="Delete"
      cancel-text="Cancel"
      variant="destructive"
      @confirm="confirmBulkDelete"
    />
  </div>
</template>
