<template>
  <UModal :open="open" title="Vergleich mit Version" @update:open="$emit('update:open', $event)">
    <template #header>
      <h3 class="text-lg font-semibold">Vergleich: Aktuelles Formular mit Version v{{ versionNumber }}</h3>
    </template>

    <template #body>
      <div v-if="loading" class="flex justify-center py-8">
        <UIcon name="i-lucide-loader-circle" class="animate-spin h-8 w-8" />
      </div>

      <div v-else-if="error" class="text-red-500">Fehler beim Laden der Version: {{ error }}</div>

      <div v-else-if="diff && hasChanges" class="space-y-6">
        <div v-if="diff.elementsAdded.length > 0" class="space-y-2">
          <h4 class="font-semibold text-success flex items-center gap-2">
            <UIcon name="i-lucide-plus-circle" />
            Hinzugefügte Elemente ({{ diff.elementsAdded.length }})
          </h4>
          <UCard v-for="(element, index) in diff.elementsAdded" :key="`added-${index}`" variant="subtle">
            <div class="flex items-start gap-2">
              <UBadge color="success" variant="subtle">+</UBadge>
              <div class="flex-1">
                <div class="font-medium">{{ element.title || 'Ohne Titel' }}</div>
                <div class="text-sm text-gray-500">Typ: {{ element.type }} · Sektion: {{ element.sectionTitle }}</div>
              </div>
            </div>
          </UCard>
        </div>

        <div v-if="diff.elementsRemoved.length > 0" class="space-y-2">
          <h4 class="font-semibold text-error flex items-center gap-2">
            <UIcon name="i-lucide-minus-circle" />
            Entfernte Elemente ({{ diff.elementsRemoved.length }})
          </h4>
          <UCard v-for="(element, index) in diff.elementsRemoved" :key="`removed-${index}`" variant="subtle">
            <div class="flex items-start gap-2">
              <UBadge color="error" variant="subtle">-</UBadge>
              <div class="flex-1">
                <div class="font-medium">{{ element.title || 'Ohne Titel' }}</div>
                <div class="text-sm text-gray-500">Typ: {{ element.type }} · Sektion: {{ element.sectionTitle }}</div>
              </div>
            </div>
          </UCard>
        </div>

        <div v-if="diff.elementsModified.length > 0" class="space-y-2">
          <h4 class="font-semibold text-warning flex items-center gap-2">
            <UIcon name="i-lucide-pencil" />
            Geänderte Elemente ({{ diff.elementsModified.length }})
          </h4>
          <UCard v-for="(element, index) in diff.elementsModified" :key="`modified-${index}`" variant="subtle">
            <div class="space-y-2">
              <div class="flex items-start gap-2">
                <UBadge color="warning" variant="subtle">~</UBadge>
                <div class="flex-1">
                  <div class="font-medium">Element in {{ element.sectionTitle }}</div>

                  <div
                    v-if="
                      element.optionsAdded.length > 0 ||
                      element.optionsRemoved.length > 0 ||
                      element.optionsModified.length > 0
                    "
                    class="mt-3 pl-4 border-l-2 border-gray-200 space-y-2"
                  >
                    <div v-if="element.optionsAdded.length > 0">
                      <div class="text-sm font-medium text-success">
                        Optionen hinzugefügt ({{ element.optionsAdded.length }}):
                      </div>
                      <div
                        v-for="(option, optIdx) in element.optionsAdded"
                        :key="`opt-add-${optIdx}`"
                        class="text-sm text-gray-700 ml-2"
                      >
                        <UBadge color="success" size="xs" class="mr-1">+</UBadge>
                        {{ option.label }} ({{ option.value }})
                      </div>
                    </div>

                    <div v-if="element.optionsRemoved.length > 0">
                      <div class="text-sm font-medium text-error">
                        Optionen entfernt ({{ element.optionsRemoved.length }}):
                      </div>
                      <div
                        v-for="(option, optIdx) in element.optionsRemoved"
                        :key="`opt-rem-${optIdx}`"
                        class="text-sm text-gray-700 ml-2"
                      >
                        <UBadge color="error" size="xs" class="mr-1">-</UBadge>
                        {{ option.label }} ({{ option.value }})
                      </div>
                    </div>

                    <div v-if="element.optionsModified.length > 0">
                      <div class="text-sm font-medium text-warning">
                        Optionen geändert ({{ element.optionsModified.length }}):
                      </div>
                      <div
                        v-for="(option, optIdx) in element.optionsModified"
                        :key="`opt-mod-${optIdx}`"
                        class="text-sm text-gray-700 ml-2"
                      >
                        <div>
                          <span class="font-medium">{{ option.value }}:</span>
                          <span class="text-error line-through ml-1">{{ option.labelChanged.from }}</span>
                          <UIcon name="i-lucide-arrow-right" class="mx-1 inline-block h-3 w-3" />
                          <span class="text-success">{{ option.labelChanged.to }}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </UCard>
        </div>
      </div>

      <div v-else class="text-center py-8 text-gray-500">Keine Unterschiede gefunden</div>
    </template>

    <template #footer>
      <div class="flex justify-end">
        <UButton label="Schließen" color="neutral" variant="outline" @click="$emit('update:open', false)" />
      </div>
    </template>
  </UModal>
</template>

<script setup lang="ts">
import type { ApplicationFormDto, ApplicationFormVersionDto } from '~~/.api-client'
import type { FormDiff } from '~~/types/formDiff'
import { compareApplicationForms } from '~/utils/formDiff'

const props = defineProps<{
  open: boolean
  currentForm: ApplicationFormDto
  versionNumber: number
  applicationFormId: string
}>()

defineEmits<{
  (e: 'update:open', value: boolean): void
}>()

const { getVersion } = useApplicationFormVersion()

const loading = ref(false)
const error = ref<string | null>(null)
const diff = ref<FormDiff | null>(null)
const versionData = ref<ApplicationFormVersionDto | null>(null)

const hasChanges = computed(() => {
  if (!diff.value) return false
  return (
    diff.value.elementsAdded.length > 0 ||
    diff.value.elementsRemoved.length > 0 ||
    diff.value.elementsModified.length > 0
  )
})

watch(
  () => props.open,
  async (isOpen) => {
    if (isOpen && !versionData.value) {
      await loadVersionAndCompare()
    }
  }
)

async function loadVersionAndCompare() {
  loading.value = true
  error.value = null
  try {
    versionData.value = await getVersion(props.applicationFormId, props.versionNumber)
    diff.value = compareApplicationForms(props.currentForm, versionData.value.snapshot)
  } catch (e: unknown) {
    error.value = e instanceof Error ? e.message : 'Unbekannter Fehler'
  } finally {
    loading.value = false
  }
}

watch(
  () => props.versionNumber,
  () => {
    versionData.value = null
    diff.value = null
  }
)
</script>
