<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useModuleStore } from '@KTXC/stores/moduleStore'
import { usePeopleStore } from '@/stores/peopleStore'
import Sidebar from '@/components/Sidebar.vue'
import CollectionEditor from '@/components/CollectionEditor.vue'
import PersonList from '@/components/PersonList.vue'
import PersonEditor from '@/components/PersonEditor.vue'
import ImportDialog from '@/components/ImportDialog.vue'

// Check if people manager is available
const moduleStore = useModuleStore()
const isPeopleManagerAvailable = computed(() => {
  return moduleStore.has('people_manager') || moduleStore.has('PeopleManager')
})

// Store
const peopleStore = usePeopleStore()

const {
  sidebarVisible,
  selectedCollection,
  selectedEntity,
  entityEditorMode,
  showCollectionEditor,
  editingCollection,
  collectionEditorMode,
  showImportDialog,
  collections,
} = storeToRefs(peopleStore)

const {
  initialize,
  selectEntity,
  createEntity,
  startEditingEntity,
  cancelEditingEntity,
  closeEntityEditor,
  saveEntity,
  deleteEntity,
  saveCollection,
  deleteCollection,
  closeImport,
} = peopleStore

// Contact search (filters the person list)
const searchQuery = ref('')

onMounted(async () => {
  try {
    await initialize()
  } catch (error) {
    console.error('[People] - Failed to load data from PeopleManager:', error)
  }
})
</script>

<template>
  <div class="people-container">
    <!-- Top Navigation Bar -->
    <v-toolbar elevation="0" density="compact" class="people-toolbar">
      <template #prepend>
        <v-btn
          icon="mdi-menu"
          variant="text"
          @click="sidebarVisible = !sidebarVisible"
        ></v-btn>
      </template>

      <v-toolbar-title class="d-flex align-center">
        <v-icon size="24" color="primary" class="mr-2">mdi-account-multiple</v-icon>
        <span class="text-subtitle-1 font-weight-bold">People</span>
      </v-toolbar-title>

      <v-spacer></v-spacer>

      <!-- Search -->
      <v-text-field
        v-model="searchQuery"
        density="compact"
        variant="outlined"
        placeholder="Search contacts..."
        prepend-inner-icon="mdi-magnify"
        hide-details
        single-line
        clearable
        class="people-toolbar-search mx-4"
      />
    </v-toolbar>

    <!-- Main Content Area -->
    <div class="people-content">
      <!-- Sidebar Navigation Drawer -->
      <Sidebar />

      <!-- Main View -->
      <div class="people-main">
        <v-alert
          v-if="!isPeopleManagerAvailable"
          type="warning"
          variant="tonal"
          closable
          class="mb-4"
        >
          <v-alert-title class="d-flex align-center">
            <v-icon icon="mdi-alert-circle" class="mr-2" />
            People Manager Not Available
          </v-alert-title>
          <div class="mt-2">
            <p>
              The People Manager module is not installed or enabled. 
              This module requires the <strong>people_manager</strong> module to function properly.
            </p>
            <p class="mt-2 mb-0">
              Please contact your system administrator to install and enable the 
              <code>people_manager</code> module.
            </p>
          </div>
        </v-alert>
        
        <div v-if="isPeopleManagerAvailable" class="people-wrapper">
          <div class="people-list-panel">
            <PersonList
              :selected-collection="selectedCollection"
              :selected-entity="selectedEntity"
              :search="searchQuery"
              @select="selectEntity"
              @fresh="createEntity"
            />
          </div>
          <div class="people-editor-panel">
            <PersonEditor
              :mode="entityEditorMode"
              :selected-collection="selectedCollection"
              :selected-entity="selectedEntity"
              @save="saveEntity"
              @delete="deleteEntity"
              @edit="startEditingEntity"
              @cancel="cancelEditingEntity"
              @close="closeEntityEditor"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- Collection Editor Dialog -->
    <CollectionEditor
      v-model="showCollectionEditor"
      :collection="editingCollection"
      :mode="collectionEditorMode"
      @save="saveCollection"
      @delete="deleteCollection"
    />

    <!-- VCF Import Dialog -->
    <ImportDialog
      v-model="showImportDialog"
      :collections="collections"
      @close="closeImport"
    />
  </div>
</template>

<style scoped lang="scss">
.people-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
  isolation: isolate; /* Create stacking context to prevent style leakage */
}

.people-toolbar {
  flex-shrink: 0;
  border-bottom: 1px solid rgb(var(--v-border-color)) !important;
}

.people-toolbar-search {
  max-width: 300px;
}

@media (max-width: 960px) {
  .people-toolbar-search {
    max-width: 180px;
    margin-inline: 8px !important;
  }
}

.people-content {
  display: flex;
  flex: 1;
  min-height: 0;
  overflow: hidden;
  position: relative;
}

.people-main {
  flex: 1;
  min-height: 0;
  min-width: 0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.people-wrapper {
  flex: 1;
  min-height: 0;
  min-width: 0;
  display: flex;
  overflow: hidden;
}

.people-list-panel {
  width: 300px;
  min-width: 250px;
  max-width: 400px;
  border-right: 1px solid rgb(var(--v-border-color));
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  background-color: rgba(var(--v-theme-on-surface), 0.04);
}

.people-editor-panel {
  flex: 1;
  border-left: 1px solid rgb(var(--v-border-color));
  overflow: hidden;
  display: flex;
  flex-direction: column;
  background-color: rgba(var(--v-theme-on-surface), 0.04);
  min-height: 0;
}

/* Responsive adjustments */
@media (max-width: 960px) {
  .people-wrapper {
    flex-direction: column;
  }

  .people-list-panel {
    width: 100%;
    max-width: none;
    height: 40%;
    border-right: none;
    border-bottom: 1px solid rgb(var(--v-border-color));
  }

  .people-editor-panel {
    border-left: none;
    border-top: 1px solid rgb(var(--v-border-color));
  }
}
</style>
