<script setup lang="ts">
import { ref, computed } from 'vue'
import { useCollectionsStore } from '@MailManager/stores/collectionsStore'
import { useServicesStore } from '@MailManager/stores/servicesStore'
import { useUser } from '@KTXC'
import FolderTreeView from './FolderTreeView.vue'
import FolderPageView from './FolderPageView.vue'
import CreateFolderDialog from './CreateFolderDialog.vue'
import RenameFolderDialog from './RenameFolderDialog.vue'
import type { CollectionObject } from '@MailManager/models/collection'
import type { ServiceInterface } from '@MailManager/types/service'

type FolderViewMode = 'tree' | 'page'

// Props
interface Props {
  selectedFolder?: CollectionObject | null
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  select: [folder: CollectionObject]
  folderCreated: [folder: CollectionObject]
}>()

// Stores
const collectionsStore = useCollectionsStore()
const servicesStore = useServicesStore()

// User settings
const { settings } = useUser()

// Folder view mode from user settings
const folderViewMode = computed(() => {
  return (settings.value.get('mail.folderViewMode') as FolderViewMode) || 'tree'
})

// Create folder dialog state
const createDialogVisible = ref(false)
const createDialogService = ref<ServiceInterface | null>(null)
const createDialogParent = ref<CollectionObject | null>(null)
const renameDialogVisible = ref(false)
const renameDialogService = ref<ServiceInterface | null>(null)
const renameDialogFolder = ref<CollectionObject | null>(null)

// Handle create folder event from child components
const handleCreateFolder = (service: ServiceInterface, parentFolder: CollectionObject | null = null) => {
  createDialogService.value = service
  createDialogParent.value = parentFolder
  createDialogVisible.value = true
}

// Handle folder created
const handleFolderCreated = (newFolder: CollectionObject) => {
  emit('folderCreated', newFolder)
  emit('select', newFolder)
}

const handleEditFolder = (service: ServiceInterface, folder: CollectionObject) => {
  renameDialogService.value = service
  renameDialogFolder.value = folder
  renameDialogVisible.value = true
}

const handleFolderRenamed = (updatedFolder: CollectionObject) => {
  emit('select', updatedFolder)
}

// Computed: all folders for validation
const allFolders = computed(() => 
  serviceGroups.value.flatMap(g => g.folders)
)

// Folder hierarchy helper type
interface FolderNode {
  folder: CollectionObject
  children: FolderNode[]
}

// Build hierarchical tree structure
const buildFolderTree = (folders: CollectionObject[]): FolderNode[] => {
  const nodeMap = new Map<string | number, FolderNode>()
  const roots: FolderNode[] = []

  // Create nodes for all folders
  folders.forEach(folder => {
    nodeMap.set(folder.identifier, {
      folder,
      children: []
    })
  })

  // Build parent-child relationships
  folders.forEach(folder => {
    const node = nodeMap.get(folder.identifier)
    if (!node) return

    if (folder.collection === null || folder.collection === undefined) {
      // Root level folder
      roots.push(node)
    } else {
      // Child folder - add to parent
      const parent = nodeMap.get(folder.collection)
      if (parent) {
        parent.children.push(node)
      } else {
        // Parent not found, treat as root
        roots.push(node)
      }
    }
  })

  return roots
}

// Group collections by service
const serviceGroups = computed(() => {
  const groups: Array<{
    service: ServiceInterface
    folders: CollectionObject[]
    folderTree: FolderNode[]
  }> = []

  servicesStore.services.forEach(service => {
    const folders = collectionsStore.collections.filter(
      c => c.provider === service.provider && String(c.service) === String(service.identifier)
    )
    
    if (folders.length > 0) {
      groups.push({ 
        service, 
        folders,
        folderTree: buildFolderTree(folders)
      })
    }
  })

  return groups
})
</script>

<template>
  <v-list density="compact" nav>
    <!-- Tree View -->
    <FolderTreeView
      v-if="folderViewMode === 'tree'"
      :selected-folder="selectedFolder"
      :service-groups="serviceGroups"
      @select="emit('select', $event)"
      @create-folder="handleCreateFolder"
      @edit-folder="handleEditFolder"
    />

    <!-- Page-based View -->
    <FolderPageView
      v-else
      :selected-folder="selectedFolder"
      :service-groups="serviceGroups"
      @select="emit('select', $event)"
      @create-folder="handleCreateFolder"
      @edit-folder="handleEditFolder"
    />

    <!-- Empty state -->
    <v-list-item v-if="serviceGroups.length === 0">
      <v-list-item-title class="text-center text-medium-emphasis">
        No mail accounts configured
      </v-list-item-title>
    </v-list-item>
  </v-list>
  
  <!-- Create Folder Dialog -->
  <CreateFolderDialog
    v-if="createDialogService"
    v-model="createDialogVisible"
    :service="createDialogService"
    :parent-folder="createDialogParent"
    :all-folders="allFolders"
    @created="handleFolderCreated"
  />

  <RenameFolderDialog
    v-if="renameDialogService && renameDialogFolder"
    v-model="renameDialogVisible"
    :service="renameDialogService"
    :folder="renameDialogFolder"
    :all-folders="allFolders"
    @updated="handleFolderRenamed"
  />
</template>

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