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

export interface Props {
  folder: CollectionObject
  service: ServiceObject
  selectedFolder?: CollectionObject | null
}

const props = defineProps<Props>()
const collectionsStore = useCollectionsStore()
const expanded = ref(false)

const emit = defineEmits<{
  select: [folder: CollectionObject]
  createSubfolder: [service: ServiceObject, parentFolder: CollectionObject]
  editFolder: [service: ServiceObject, folder: CollectionObject]
}>()

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

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

const handleExpandableFolderClick = () => {
  expanded.value = !expanded.value
  emit('select', props.folder)
}

// Get icon for folder based on role
const getFolderIcon = (folder: CollectionObject): string => {
  switch (folder.properties.role) {
    case 'inbox':
      return 'mdi-inbox'
    case 'sent':
      return 'mdi-send'
    case 'drafts':
      return 'mdi-file-document'
    case 'trash':
      return 'mdi-delete'
    case 'junk':
      return 'mdi-alert-octagon'
    case 'archive':
      return 'mdi-archive'
    case 'outbox':
      return 'mdi-tray-arrow-up'
    default:
      return 'mdi-folder'
  }
}

// Get color for folder based on role
const getFolderColor = (folder: CollectionObject): string | undefined => {
  switch (folder.properties.role) {
    case 'inbox':
      return 'primary'
    case 'sent':
      return 'success'
    case 'drafts':
      return 'warning'
    case 'trash':
      return 'error'
    case 'junk':
      return 'orange'
    default:
      return undefined
  }
}

// Check if folder is selected
const isSelected = (folder: CollectionObject): boolean => {
  if (!props.selectedFolder) return false
  return (
    folder.provider === props.selectedFolder.provider &&
    String(folder.service) === String(props.selectedFolder.service) &&
    String(folder.identifier) === String(props.selectedFolder.identifier)
  )
}
</script>

<template>
  <v-list-group v-if="hasChildren" v-model="expanded" class="folder-tree-group">
    <template v-slot:activator="{ props: activatorProps }">
      <v-list-item
        v-bind="activatorProps"
        class="folder-row-item"
        :title="folder.properties.label"
        :active="isSelected(folder)"
        @click.stop="handleExpandableFolderClick()"
      >
        <template v-slot:prepend>
          <v-icon 
            :icon="getFolderIcon(folder)" 
            :color="getFolderColor(folder)"
          />
        </template>
        
        <template v-slot:append>
          <v-badge
            v-if="folder.properties.unread && folder.properties.unread > 0"
            :content="folder.properties.unread"
            color="primary"
            inline
            class="mr-2"
          />
          
          <!-- Action menu -->
          <v-menu>
            <template v-slot:activator="{ props: menuProps }">
              <v-btn
                v-bind="menuProps"
                icon="mdi-dots-vertical"
                variant="text"
                size="x-small"
                density="compact"
                @click.stop
              >
                <v-icon size="small">mdi-dots-vertical</v-icon>
              </v-btn>
            </template>
            
            <v-list density="compact">
              <v-list-item
                prepend-icon="mdi-pencil"
                @click="emit('editFolder', service, folder)"
              >
                <v-list-item-title>Edit Folder Name</v-list-item-title>
              </v-list-item>
              <v-list-item
                prepend-icon="mdi-folder-plus"
                @click="emit('createSubfolder', service, folder)"
              >
                <v-list-item-title>New Subfolder</v-list-item-title>
              </v-list-item>
            </v-list>
          </v-menu>
        </template>
      </v-list-item>
    </template>

    <div v-if="expanded" class="folder-tree-children">
      <FolderTreeNode
        v-for="childFolder in childFolders"
        :key="childFolder.identifier"
        :folder="childFolder"
        :service="service"
        :selected-folder="selectedFolder"
        @select="emit('select', $event)"
        @create-subfolder="(service, parentFolder) => emit('createSubfolder', service, parentFolder)"
        @edit-folder="(service, folder) => emit('editFolder', service, folder)"
      />
    </div>
  </v-list-group>

  <v-list-item
    v-else
    class="folder-tree-item folder-row-item"
    :title="folder.properties.label"
    :active="isSelected(folder)"
    @click="emit('select', folder)"
  >
    <template v-slot:prepend>
      <v-icon 
        :icon="getFolderIcon(folder)" 
        :color="getFolderColor(folder)"
      />
    </template>
    
    <template v-slot:append>
      <v-badge
        v-if="folder.properties.unread && folder.properties.unread > 0"
        :content="folder.properties.unread"
        color="primary"
        inline
        class="mr-2"
      />
      
      <!-- Action menu -->
      <v-menu>
        <template v-slot:activator="{ props: menuProps }">
          <v-btn
            v-bind="menuProps"
            icon="mdi-dots-vertical"
            variant="text"
            size="x-small"
            density="compact"
            @click.stop
          >
            <v-icon size="small">mdi-dots-vertical</v-icon>
          </v-btn>
        </template>
        
        <v-list density="compact">
          <v-list-item
            prepend-icon="mdi-pencil"
            @click="emit('editFolder', service, folder)"
          >
            <v-list-item-title>Edit Folder Name</v-list-item-title>
          </v-list-item>
          <v-list-item
            prepend-icon="mdi-folder-plus"
            @click="emit('createSubfolder', service, folder)"
          >
            <v-list-item-title>New Subfolder</v-list-item-title>
          </v-list-item>
        </v-list>
      </v-menu>
    </template>
  </v-list-item>
</template>

<script lang="ts">
export default {
  name: 'FolderTreeNode'
}
</script>

<style scoped>
.v-list-item--active {
  background-color: rgba(var(--v-theme-primary), 0.12);
}

/* Keep top-level leaf folders aligned with expandable folders */
.folder-tree-item {
  --indent-padding: 0 !important;
}

/* Remove indentation for the folder-tree-group itself */
.folder-tree-group {
  --indent-padding: 0 !important;
}

/* Reduce default indentation for nested items */
.folder-tree-group :deep(.v-list-group__items) {
  --indent-padding: 0;
}

.folder-row-item {
  --v-list-item-prepend-size: 22px;
}

.folder-row-item :deep(.v-list-item__prepend) {
  padding-inline-start: 4px;
  margin-inline-end: 2px;
}

/* Add visual indicator for nested items */
.folder-tree-children {
  position: relative;
  padding-left: 12px;
  border-left: 2px solid rgba(var(--v-border-color), 0.3);
  margin-left: 8px;
}

/* Add connector line for nested items */
.folder-tree-children::before {
  content: '';
  position: absolute;
  left: -2px;
  top: 0;
  bottom: 0;
  width: 2px;
  background: rgba(var(--v-border-color), 0.3);
}
</style>
