<script setup lang="ts">
import { ref, watch } from 'vue'
import type { GlossaryConflict } from '@/types'
import DkuSpinner from '@/components/DkuSpinner.vue'

type ConflictResolutionAction = 'keep' | 'replace'

const props = defineProps<{
  conflicts: GlossaryConflict[]
  open: boolean
}>()

const emit = defineEmits<{
  (e: 'update:open', value: boolean): void
  (e: 'apply', resolutions: Record<string, ConflictResolutionAction>): void
}>()

// Resolution choices for each conflict (by existing term id)
const resolutions = ref<Record<string, ConflictResolutionAction>>({})

// Initialize resolutions when conflicts change
watch(
  () => props.conflicts,
  (newConflicts) => {
    const newResolutions: Record<string, ConflictResolutionAction> = {}
    for (const conflict of newConflicts) {
      // Default to "keep" (preserve user's version)
      newResolutions[conflict.existing_term.id] = 'keep'
    }
    resolutions.value = newResolutions
  },
  { immediate: true }
)

const isSubmitting = ref(false)

function close() {
  emit('update:open', false)
}

async function handleSubmit() {
  isSubmitting.value = true
  try {
    emit('apply', { ...resolutions.value })
    close()
  } catch (e) {
    close()
  } finally {
    isSubmitting.value = false
  }
}

function setAllResolutions(action: ConflictResolutionAction) {
  const newResolutions: Record<string, ConflictResolutionAction> = {}
  for (const conflict of props.conflicts) {
    newResolutions[conflict.existing_term.id] = action
  }
  resolutions.value = newResolutions
}

function selectResolution(termId: string, action: ConflictResolutionAction) {
  resolutions.value[termId] = action
}
</script>

<template>
  <Teleport to="body">
    <div
      v-if="open"
      class="fixed inset-0 z-50 flex items-center justify-center"
    >
      <!-- Backdrop -->
      <div class="absolute inset-0 bg-black/50" />

      <!-- Dialog -->
      <div class="relative z-10 w-full max-w-3xl max-h-[80vh] overflow-hidden rounded-lg bg-background shadow-xl">
        <!-- Header -->
        <div class="border-b px-6 py-4">
          <h2 class="text-lg font-semibold">Resolve Conflicts</h2>
          <p class="text-sm text-muted-foreground">
            {{ conflicts.length }} term(s) have conflicts with extracted content.
            Click on the version you want to keep.
          </p>
        </div>

        <!-- Bulk actions -->
        <div class="flex items-center gap-2 border-b bg-muted/30 px-6 py-2">
          <span class="text-sm text-muted-foreground">Apply to all:</span>
          <button
            class="rounded px-3 py-1 text-sm hover:bg-muted"
            @click="setAllResolutions('keep')"
          >
            Keep All Mine
          </button>
          <button
            class="rounded px-3 py-1 text-sm hover:bg-muted"
            @click="setAllResolutions('replace')"
          >
            Use All Extracted
          </button>
        </div>

        <!-- Conflicts list -->
        <div class="max-h-[50vh] overflow-auto p-6">
          <div class="space-y-4">
            <div
              v-for="conflict in conflicts"
              :key="conflict.existing_term.id"
              class="rounded-lg border p-4"
            >
              <h3 class="mb-3 font-medium">{{ conflict.existing_term.term }}</h3>

              <div class="grid grid-cols-2 gap-4 text-sm">
                <!-- Existing (user's version) -->
                <button
                  :class="[
                    'cursor-pointer rounded-lg border p-3 text-left transition-colors',
                    resolutions[conflict.existing_term.id] === 'keep'
                      ? 'border-active bg-card'
                      : 'border-transparent bg-muted/50 hover:border-active',
                  ]"
                  @click="selectResolution(conflict.existing_term.id, 'keep')"
                >
                  <div class="mb-1 font-medium text-muted-foreground">Your Version</div>
                  <p class="text-foreground">
                    {{ conflict.existing_term.description || '(no description)' }}
                  </p>
                  <div v-if="conflict.existing_term.synonyms?.length" class="mt-2 text-xs text-muted-foreground">
                    Synonyms: {{ conflict.existing_term.synonyms.join(', ') }}
                  </div>
                </button>

                <!-- Extracted version -->
                <button
                  :class="[
                    'cursor-pointer rounded-lg border p-3 text-left transition-colors',
                    resolutions[conflict.existing_term.id] === 'replace'
                      ? 'border-active bg-card'
                      : 'border-transparent bg-muted/50 hover:border-active',
                  ]"
                  @click="selectResolution(conflict.existing_term.id, 'replace')"
                >
                  <div class="mb-1 font-medium text-muted-foreground">Extracted Version</div>
                  <p class="text-foreground">
                    {{ conflict.extracted_term.description || '(no description)' }}
                  </p>
                  <div v-if="conflict.extracted_term.synonyms?.length" class="mt-2 text-xs text-muted-foreground">
                    Synonyms: {{ conflict.extracted_term.synonyms.join(', ') }}
                  </div>
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- Footer -->
        <div class="flex items-center justify-end gap-3 border-t px-6 py-4">
          <button
            class="btn-primary inline-flex items-center gap-2"
            :disabled="isSubmitting"
            @click="handleSubmit"
          >
            <DkuSpinner v-if="isSubmitting" size="md" />
            <i v-else class="dku-icon-checkmark-16" />
            Apply Resolutions
          </button>
        </div>
      </div>
    </div>
  </Teleport>
</template>
