<template>
  <div class="space-y-4">
    <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">{{ $t('versions.loadError') }}: {{ error }}</div>

    <div v-else-if="versions.length === 0" class="text-center py-8 text-gray-500">{{ $t('versions.empty') }}</div>

    <div v-else class="space-y-3">
      <UCard v-for="version in versions" :key="version.id" class="hover:shadow-md transition-shadow">
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-4">
            <UBadge variant="subtle" color="primary" class="font-semibold"> v{{ version.versionNumber }} </UBadge>
            <div>
              <div class="font-medium">{{ version.name }}</div>
              <div class="text-sm text-gray-500">
                {{ formatDate(new Date(version.createdAt)) }} · {{ version.createdBy.name }}
              </div>
            </div>
          </div>
          <div class="flex items-center gap-3">
            <UBadge :color="getStatusColor(version.status)">
              {{ getStatusLabel(version.status) }}
            </UBadge>
            <UButton
              icon="i-lucide-git-compare"
              size="sm"
              color="neutral"
              variant="outline"
              :label="$t('versions.compare')"
              @click="openComparisonModal(version)"
            />
            <UButton
              icon="i-lucide-undo-2"
              size="sm"
              color="neutral"
              variant="outline"
              :label="$t('versions.restore')"
              @click="openRestoreModal(version)"
            />
          </div>
        </div>
      </UCard>
    </div>

    <VersionComparisonModal
      v-model:open="isComparisonModalOpen"
      :current-form="currentForm"
      :version-number="selectedVersion?.versionNumber ?? 0"
      :application-form-id="applicationFormId"
    />

    <RestoreVersionModal
      v-model:open="isRestoreModalOpen"
      :version-number="selectedVersion?.versionNumber ?? 0"
      :loading="restoring"
      @confirm="handleRestore"
    />
  </div>
</template>

<script setup lang="ts">
import type { ApplicationFormDto, ApplicationFormVersionListItemDto, ApplicationFormStatus } from '~~/.api-client'
import { formatDate } from '~/utils/date'

const props = defineProps<{
  applicationFormId: string
  currentForm: ApplicationFormDto
}>()

const emit = defineEmits<{
  (e: 'restored'): void
}>()

const { getVersions, restoreVersion } = useApplicationFormVersion()
const toast = useToast()
const { t: $t } = useI18n()

const versions = ref<ApplicationFormVersionListItemDto[]>([])
const loading = ref(false)
const error = ref<string | null>(null)
const isRestoreModalOpen = ref(false)
const isComparisonModalOpen = ref(false)
const selectedVersion = ref<ApplicationFormVersionListItemDto | null>(null)
const restoring = ref(false)

async function loadVersions() {
  loading.value = true
  error.value = null
  try {
    versions.value = await getVersions(props.applicationFormId)
  } catch (e: unknown) {
    error.value = e instanceof Error ? e.message : $t('versions.unknownError')
    toast.add({
      title: $t('common.error'),
      description: $t('versions.loadErrorDescription'),
      color: 'error'
    })
  } finally {
    loading.value = false
  }
}

function openComparisonModal(version: ApplicationFormVersionListItemDto) {
  selectedVersion.value = version
  isComparisonModalOpen.value = true
}

function openRestoreModal(version: ApplicationFormVersionListItemDto) {
  selectedVersion.value = version
  isRestoreModalOpen.value = true
}

async function handleRestore() {
  if (!selectedVersion.value) return

  restoring.value = true
  try {
    await restoreVersion(props.applicationFormId, selectedVersion.value.versionNumber)
    toast.add({
      title: $t('common.success'),
      description: $t('versions.restored', { number: selectedVersion.value.versionNumber }),
      color: 'success'
    })
    isRestoreModalOpen.value = false
    await loadVersions()
    emit('restored')
  } catch {
    toast.add({
      title: $t('common.error'),
      description: $t('versions.restoreError'),
      color: 'error'
    })
  } finally {
    restoring.value = false
  }
}

function getStatusColor(status: ApplicationFormStatus) {
  switch (status) {
    case 'DRAFT':
      return 'neutral' as const
    case 'SUBMITTED':
      return 'info' as const
    case 'APPROVED':
      return 'success' as const
    case 'REJECTED':
      return 'error' as const
    case 'SIGNED':
      return 'primary' as const
    default:
      return 'neutral' as const
  }
}

const { t: $t } = useI18n()

function getStatusLabel(status: ApplicationFormStatus): string {
  switch (status) {
    case 'DRAFT':
      return $t('applicationForms.status.draft')
    case 'SUBMITTED':
      return $t('applicationForms.status.submitted')
    case 'APPROVED':
      return $t('applicationForms.status.approved')
    case 'REJECTED':
      return $t('applicationForms.status.rejected')
    case 'SIGNED':
      return $t('applicationForms.status.signed')
    default:
      return status
  }
}

onMounted(() => {
  loadVersions()
})
</script>
