<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useCollectionsStore } from '@MailManager/stores/collectionsStore'
import type { CollectionObject } from '@MailManager/models/collection'
import type { ServiceObject } from '@MailManager/models'

interface Props {
  modelValue: boolean
  service: ServiceObject
  folder: CollectionObject
  loading?: boolean
  errorMessage?: string
}

const props = withDefaults(defineProps<Props>(), {
  loading: false,
  errorMessage: '',
})

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  confirm: []
}>()

const collectionsStore = useCollectionsStore()

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

const folderLabel = computed(() => props.folder.properties.label || String(props.folder.identifier))

const hasChildren = computed(() => {
  return collectionsStore.hasChildrenInCollection(props.folder.provider, props.folder.service, props.folder.identifier)
})

watch(dialogValue, isOpen => {
  if (isOpen) {
  }
})

const handleDelete = () => {
  emit('confirm')
}

const handleCancel = () => {
  dialogValue.value = false
}
</script>

<template>
  <v-dialog
    v-model="dialogValue"
    max-width="520"
    persistent
  >
    <v-card>
      <v-card-title class="text-h5">
        Delete Folder
      </v-card-title>

      <v-card-text>
        <div class="mb-4">
          <div class="text-caption text-medium-emphasis">Account</div>
          <div class="text-body-2">
            {{ service.label || service.primaryAddress || 'Mail Account' }}
          </div>
        </div>

        <div class="mb-4">
          <div class="text-caption text-medium-emphasis">Folder</div>
          <div class="text-body-2">
            {{ folderLabel }}
          </div>
        </div>

        <p class="text-body-2 mb-0">
          Confirm deletion of this folder.
        </p>

        <p
          v-if="hasChildren"
          class="text-body-2 mt-3 mb-0"
        >
          This folder contains subfolders. The delete request may be rejected if the provider does not allow deleting non-empty folders.
        </p>

        <v-alert
          v-if="errorMessage"
          type="error"
          variant="tonal"
          density="compact"
          class="mt-4"
        >
          {{ errorMessage }}
        </v-alert>
      </v-card-text>

      <v-card-actions>
        <v-spacer />

        <v-btn
          variant="text"
          :disabled="loading"
          @click="handleCancel"
        >
          Cancel
        </v-btn>

        <v-btn
          color="error"
          variant="elevated"
          :loading="loading"
          @click="handleDelete"
        >
          Delete Folder
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<style scoped>
.text-caption {
  font-size: 0.75rem;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.0333em;
}
</style>