<template>
  <IvyDialog
    v-model="isVisible"
    :title="getLabel('import_forms')"
    show-close
    align-center
    width="500px"
    :z-index="10001"
    append-to-body
  >
    <div
      class="ivyforms-import-dialog ivyforms-flex ivyforms-flex-direction-column ivyforms-gap-24 ivyforms-pb-16"
    >
      <p class="ivyforms-import-dialog__description regular-16">
        {{ getLabel('import_forms_instructions') }}
      </p>

      <div class="ivyforms-import-dialog__field ivyforms-flex ivyforms-flex-direction-column">
        <label class="ivyforms-import-dialog__label medium-18">
          {{ getLabel('choose_ivyforms_file') }}
        </label>
        <p class="ivyforms-import-dialog__hint regular-16">
          {{ getLabel('maximum_file_size') }}
        </p>

        <div
          class="ivyforms-import-dialog__file-selector ivyforms-flex ivyforms-align-items-center ivyforms-gap-12 ivyforms-mt-4"
        >
          <input
            ref="fileInputRef"
            type="file"
            accept=".json"
            class="ivyforms-import-dialog__file-input"
            @change="handleFileSelect"
          />

          <IvyButtonAction priority="tertiary" type="fill" size="d" @click="triggerFileInput">
            {{ getLabel('choose_file') }}
          </IvyButtonAction>

          <span class="ivyforms-import-dialog__file-name ivyforms-flex-1 regular-14">
            {{ selectedFileName || getLabel('no_file_chosen') }}
          </span>
        </div>
      </div>
    </div>

    <template #footer>
      <IvyButtonAction
        priority="success"
        size="d"
        type="fill"
        :disabled="!selectedFile || isImporting"
        @click="handleImport"
      >
        {{ isImporting ? getLabel('importing') : getLabel('import') }}
      </IvyButtonAction>
    </template>
  </IvyDialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import IvyDialog from '@/views/_components/dialog/IvyDialog.vue'
import IvyButtonAction from '@/views/_components/button/IvyButtonAction.vue'
import { useLabels } from '@/composables/useLabels'
import IvyMessage from '@/views/_components/message/ivyMessage.ts'

interface Props {
  modelValue: boolean
  isImporting?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  isImporting: false,
})

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'import', file: File): void
  (e: 'cancel'): void
}>()

const { getLabel } = useLabels()

// Maximum file size: 5 MB
const MAX_FILE_SIZE_BYTES = 5 * 1024 * 1024

const fileInputRef = ref<HTMLInputElement | null>(null)
const selectedFile = ref<File | null>(null)
const selectedFileName = ref<string>('')

const isVisible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => {
    emit('update:modelValue', value)
    if (!value) {
      resetDialog()
    }
  },
})

const triggerFileInput = () => {
  fileInputRef.value?.click()
}

const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (file) {
    // Validate file size
    if (file.size > MAX_FILE_SIZE_BYTES) {
      const fileSizeMB = (file.size / (1024 * 1024)).toFixed(2)
      const maxSizeMB = MAX_FILE_SIZE_BYTES / (1024 * 1024)
      const errorMessage = getLabel('file_size_exceeds_limit')
        .replace('{fileSize}', fileSizeMB)
        .replace('{maxSize}', maxSizeMB.toString())
      IvyMessage({
        message: errorMessage,
        type: 'error',
      })
      // Clear the file input
      if (fileInputRef.value) {
        fileInputRef.value.value = ''
      }
      return
    }
    selectedFile.value = file
    selectedFileName.value = file.name
  }
}

const handleImport = () => {
  if (selectedFile.value) {
    emit('import', selectedFile.value)
  }
}

const clearFile = () => {
  selectedFile.value = null
  selectedFileName.value = ''
  if (fileInputRef.value) {
    fileInputRef.value.value = ''
  }
}

const resetDialog = () => {
  clearFile()
}

// Watch for external reset (e.g., after successful import)
watch(
  () => props.modelValue,
  (newValue) => {
    if (!newValue) {
      resetDialog()
    }
  },
)
</script>

<style lang="scss" scoped>
.ivyforms-import-dialog {
  &__description {
    color: var(--map-base-text--1);
  }

  &__label {
    color: var(--map-base-text-0);
  }

  &__hint {
    color: var(--map-base-text--1);
  }

  &__file-input {
    display: none;
  }

  &__file-name {
    color: var(--map-base-dusk-symbol-0);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

// Ensure dialog is above template selection modal
:deep(.el-overlay) {
  z-index: 10001 !important;
}

:deep(.ivyforms-dialog-wrapper) {
  z-index: 10001 !important;
}
</style>
