<script setup lang="ts">
import { ref, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { toast } from 'vue-sonner'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import type { GlossaryTerm } from '@/types'

const props = defineProps<{
  show: boolean
  existingTerms: GlossaryTerm[]
}>()

const emit = defineEmits<{
  close: []
  'add-terms': [terms: GlossaryTerm[]]
}>()

const { t } = useI18n()

// Tab state
type TabId = 'one' | 'multi'
const activeTab = ref<TabId>('one')

const tabs: { id: TabId; label: string }[] = [
  { id: 'one', label: 'One by one' },
  { id: 'multi', label: 'Several' },
]

// Form state for "One term" mode
const termName = ref('')
const termDescription = ref('')
const termSynonyms = ref('')

// Multi-terms mode state
const csvText = ref('')

// Locally added terms (not yet committed to parent)
const addedTerms = ref<GlossaryTerm[]>([])

// Editing state: when set, the left panel form is in "edit" mode
const editingTermId = ref<string | null>(null)
const isEditing = computed(() => editingTermId.value !== null)

const addedCount = computed(() => addedTerms.value.length)

function generateId(): string {
  if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) {
    return crypto.randomUUID()
  }
  return `term_${Date.now()}_${Math.random().toString(16).slice(2)}`
}

// Check if a term already exists (in parent or locally added)
function termExists(name: string): boolean {
  const normalized = name.toLowerCase()
  const existsInParent = props.existingTerms.some(
    (t) => t.term.toLowerCase() === normalized
  )
  const existsLocally = addedTerms.value.some(
    (t) => t.term.toLowerCase() === normalized
  )
  return existsInParent || existsLocally
}

function createTerm(name: string, description: string, synonyms: string[]): GlossaryTerm {
  const now = new Date().toISOString()
  return {
    id: generateId(),
    term: name,
    description: description || undefined,
    synonyms: synonyms,
    source: 'MANUAL',
    userModified: true,
    created: { on: now },
    privateEditorData: {},
  }
}

function handleAdd() {
  const name = termName.value.trim()
  if (!name) {
    toast.error('Term name is required')
    return
  }

  if (termExists(name)) {
    toast.error('This term already exists')
    return
  }

  const synonymsArray = termSynonyms.value
    ? termSynonyms.value.split(',').map((s) => s.trim()).filter(Boolean)
    : []

  const newTerm = createTerm(name, termDescription.value.trim(), synonymsArray)

  // Add to local list (newest first)
  addedTerms.value.unshift(newTerm)

  // Clear form
  termName.value = ''
  termDescription.value = ''
  termSynonyms.value = ''

  toast.success(`Added "${newTerm.term}"`)
}

// CSV parsing with support for quoted fields
function parseCSVLine(line: string): string[] {
  const result: string[] = []
  let current = ''
  let inQuotes = false

  for (let i = 0; i < line.length; i++) {
    const char = line[i]
    const nextChar = line[i + 1]

    if (inQuotes) {
      if (char === '"') {
        if (nextChar === '"') {
          // Escaped quote
          current += '"'
          i++
        } else {
          // End of quoted field
          inQuotes = false
        }
      } else {
        current += char
      }
    } else {
      if (char === '"') {
        inQuotes = true
      } else if (char === ',') {
        result.push(current.trim())
        current = ''
      } else {
        current += char
      }
    }
  }

  result.push(current.trim())
  return result
}

function handleAddFromCSV() {
  const lines = csvText.value.split('\n').map(l => l.trim()).filter(Boolean)

  if (lines.length === 0) {
    toast.error('Please enter at least one term')
    return
  }

  let addedCount = 0
  let skippedCount = 0
  const skippedReasons: string[] = []

  for (const line of lines) {
    const fields = parseCSVLine(line)
    const name = fields[0]?.trim()

    if (!name) {
      skippedCount++
      continue
    }

    if (termExists(name)) {
      skippedCount++
      skippedReasons.push(`"${name}" (duplicate)`)
      continue
    }

    const description = fields[1]?.trim() || ''
    const synonymsStr = fields[2]?.trim() || ''
    const synonymsArray = synonymsStr
      ? synonymsStr.split(';').map((s) => s.trim()).filter(Boolean)
      : []

    const newTerm = createTerm(name, description, synonymsArray)
    addedTerms.value.unshift(newTerm)
    addedCount++
  }

  // Clear CSV input
  csvText.value = ''

  // Show summary toast
  if (addedCount > 0 && skippedCount === 0) {
    toast.success(t('terms.added', addedCount))
  } else if (addedCount > 0 && skippedCount > 0) {
    toast.success(t('terms.added', addedCount), {
      description: `${skippedCount} skipped (invalid or duplicate)`,
    })
  } else if (skippedCount > 0) {
    toast.warning('No terms added', {
      description: `${skippedCount} skipped (invalid or duplicate)`,
    })
  }
}

function removeTerm(termId: string) {
  addedTerms.value = addedTerms.value.filter((t) => t.id !== termId)
}

// Edit: populate the left panel form with the term's data
function startEdit(term: GlossaryTerm) {
  editingTermId.value = term.id
  termName.value = term.term
  termDescription.value = term.description || ''
  termSynonyms.value = (term.synonyms || []).join(', ')
}

function cancelEdit() {
  editingTermId.value = null
  termName.value = ''
  termDescription.value = ''
  termSynonyms.value = ''
}

function handleSave() {
  const termId = editingTermId.value
  if (!termId) return

  const name = termName.value.trim()
  if (!name) {
    toast.error('Term name cannot be empty')
    return
  }

  // Check if new name conflicts with other terms (excluding the one being edited)
  const normalized = name.toLowerCase()
  const existsInParent = props.existingTerms.some(
    (t) => t.term.toLowerCase() === normalized
  )
  const existsInOtherAdded = addedTerms.value.some(
    (t) => t.id !== termId && t.term.toLowerCase() === normalized
  )

  if (existsInParent || existsInOtherAdded) {
    toast.error('A term with this name already exists')
    return
  }

  const index = addedTerms.value.findIndex((t) => t.id === termId)
  if (index === -1) return

  const synonymsArray = termSynonyms.value
    ? termSynonyms.value.split(',').map((s) => s.trim()).filter(Boolean)
    : []

  addedTerms.value[index] = {
    ...addedTerms.value[index],
    term: name,
    description: termDescription.value.trim() || undefined,
    synonyms: synonymsArray,
  }

  cancelEdit()
}

function resetState() {
  addedTerms.value = []
  termName.value = ''
  termDescription.value = ''
  termSynonyms.value = ''
  csvText.value = ''
  activeTab.value = 'one'
  editingTermId.value = null
}

function handleDone() {
  if (addedTerms.value.length > 0) {
    emit('add-terms', addedTerms.value)
  }
  resetState()
  emit('close')
}

function handleCancel() {
  resetState()
  emit('close')
}
</script>

<template>
  <Teleport to="body">
    <div
      v-if="show"
      class="fixed inset-0 z-50 flex items-center justify-center bg-black/50"
    >
      <div class="flex h-[600px] w-full max-w-3xl flex-col rounded-lg bg-background shadow-lg">
        <!-- Header with tabs -->
        <div class="border-b px-6 py-4">
          <h2 class="text-lg font-semibold">Add Terms</h2>
          <p class="text-sm text-muted-foreground">
            Add glossary terms manually
          </p>
        </div>

        <!-- Tabs -->
        <div class="px-6">
          <div class="flex">
            <button
              v-for="tab in tabs"
              :key="tab.id"
              :class="[
                'relative inline-flex items-center transition-colors hover:no-underline focus:outline-none',
                activeTab === tab.id
                  ? 'font-medium'
                  : 'font-normal',
              ]"
              :style="{
                fontSize: '13px',
                lineHeight: '40px',
                letterSpacing: '0.2px',
                color: '#666666',
                padding: activeTab === tab.id ? '0 10px 1px' : '0 13px',
              }"
              @click="activeTab = tab.id"
            >
              {{ tab.label }}
              <span
                v-if="activeTab === tab.id"
                class="absolute bottom-0 left-0 right-0 h-0.5 bg-[#666666]"
              />
            </button>
          </div>
        </div>

        <!-- Content: side-by-side layout -->
        <div class="flex flex-1 min-h-0">
          <!-- Left panel: input form -->
          <div class="flex w-1/2 flex-col border-r px-6 py-4">
            <!-- Single term form -->
            <template v-if="activeTab === 'one'">
              <form class="flex flex-1 flex-col" @submit.prevent="isEditing ? handleSave() : handleAdd()">
                <div class="flex-1 space-y-3">
                  <div>
                    <label class="mb-1 block text-sm font-medium">Term *</label>
                    <input
                      v-model="termName"
                      type="text"
                      class="w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
                      placeholder="Enter term name"
                    />
                  </div>
                  <div>
                    <label class="mb-1 block text-sm font-medium">Description</label>
                    <textarea
                      v-model="termDescription"
                      class="w-full resize-none rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
                      placeholder="Enter description"
                      rows="4"
                    />
                  </div>
                  <div>
                    <label class="mb-1 block text-sm font-medium">Synonyms</label>
                    <input
                      v-model="termSynonyms"
                      type="text"
                      class="w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
                      placeholder="Comma-separated synonyms"
                    />
                  </div>
                </div>
                <div class="mt-4 flex justify-end gap-2">
                  <button
                    v-if="isEditing"
                    type="button"
                    class="btn-tertiary"
                    @click="cancelEdit"
                  >
                    Cancel
                  </button>
                  <button
                    type="submit"
                    class="btn-tertiary"
                  >
                    {{ isEditing ? 'Save' : 'Add' }}
                  </button>
                </div>
              </form>
            </template>

            <!-- Multi terms (CSV) form -->
            <template v-else>
              <div class="flex flex-1 flex-col min-h-0">
                <label class="mb-1 shrink-0 block text-sm font-medium">Terms (CSV format)</label>
                <textarea
                  v-model="csvText"
                  class="flex-1 min-h-0 w-full resize-none rounded-md border border-input bg-background px-3 py-2 font-mono text-sm focus:outline-none focus:ring-2 focus:ring-ring"
                  placeholder="term,description,synonyms
Revenue,Total income from sales,income;earnings
Cost,Total expenses incurred,expense"
                />
                <p class="mt-1.5 shrink-0 text-xs text-muted-foreground">
                  One term per line. Synonyms separated by semicolons.
                </p>
                <div class="mt-4 shrink-0 flex justify-end">
                  <button
                    type="button"
                    class="btn-tertiary"
                    @click="handleAddFromCSV"
                  >
                    Add
                  </button>
                </div>
              </div>
            </template>
          </div>

          <!-- Right panel: added terms list -->
          <div class="flex w-1/2 flex-col px-6 py-4">
            <div class="mb-2 shrink-0 text-sm font-medium text-muted-foreground">
              Added ({{ addedCount }})
            </div>
            <div class="flex-1 min-h-0 overflow-y-auto">
              <!-- Empty state -->
              <div v-if="addedCount === 0" class="flex h-full flex-col items-center justify-center p-6 text-center">
                <div class="mb-2 rounded-full bg-muted p-3">
                  <i class="dku-icon-book-16 text-muted-foreground" />
                </div>
                <p class="text-sm text-muted-foreground">No terms added yet</p>
              </div>
              <!-- Terms list -->
              <div
                v-for="(term, index) in addedTerms"
                :id="`term-${term.id}`"
                :key="term.id"
                :class="[
                  'border-b px-3 py-2 last:border-b-0',
                  index % 2 === 1 ? 'bg-muted/40' : ''
                ]"
              >
                <div class="flex items-center justify-between gap-2">
                  <div class="min-w-0 flex-1">
                    <div class="font-medium truncate" :class="{ 'text-primary': editingTermId === term.id }">{{ term.term }}</div>
                    <div v-if="term.description" class="text-sm text-muted-foreground truncate">
                      {{ term.description }}
                    </div>
                    <div v-if="term.synonyms?.length" class="text-xs text-muted-foreground truncate">
                      Synonyms: {{ term.synonyms.join(', ') }}
                    </div>
                  </div>
                  <div class="flex shrink-0 items-center gap-1">
                    <Tooltip>
                      <TooltipTrigger as-child>
                        <button
                          class="rounded p-1 text-muted-foreground hover:bg-muted"
                          @click="startEdit(term)"
                        >
                          <i class="dku-icon-edit-12" />
                        </button>
                      </TooltipTrigger>
                      <TooltipContent>Edit</TooltipContent>
                    </Tooltip>
                    <Tooltip>
                      <TooltipTrigger as-child>
                        <button
                          class="rounded p-1 text-destructive hover:bg-destructive/10"
                          @click="removeTerm(term.id)"
                        >
                          <i class="dku-icon-trash-12" />
                        </button>
                      </TooltipTrigger>
                      <TooltipContent>Remove</TooltipContent>
                    </Tooltip>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Footer -->
        <div class="flex items-center justify-end gap-2 border-t px-6 py-4">
          <button
            type="button"
            class="btn-secondary"
            @click="handleCancel"
          >
            Cancel
          </button>
          <button
            type="button"
            class="btn-primary"
            @click="handleDone"
          >
            Done
          </button>
        </div>
      </div>
    </div>
  </Teleport>
</template>
