<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useServicesStore } from '@MailManager/stores/servicesStore'
import { AddAccountDialog, EditAccountDialog } from '@MailManager/main'
import type { ServiceObject } from '@MailManager/models'

const servicesStore = useServicesStore()

// Dialog state
const showAddDialog = ref(false)
const showEditDialog = ref(false)
const editService = ref<ServiceObject>()

// Load services on mount
onMounted(async () => {
  if (!servicesStore.has) {
    await servicesStore.list()
  }
})

const handleAddAccount = () => {
  showAddDialog.value = true
}

const handleConfigureAccount = (service: ServiceObject) => {
  editService.value = service
  showEditDialog.value = true
}

const handleAccountSaved = async () => {
  // Refresh the services list
  await servicesStore.list()
}
</script>

<template>
  <div class="pa-4">
    <h3 class="text-h6 mb-4">Email Accounts</h3>
    <v-list>
      <v-list-item
        v-for="service in servicesStore.services"
        :key="`${service.provider}:${service.identifier}`"
      >
        <template #prepend>
          <v-avatar color="primary">
            <v-icon>mdi-email</v-icon>
          </v-avatar>
        </template>

        <v-list-item-title>{{ service.label || 'Unnamed Account' }}</v-list-item-title>
        <v-list-item-subtitle>{{ service.primaryAddress?.address || service.identifier }}</v-list-item-subtitle>

        <template #append>
          <v-btn
            icon="mdi-cog"
            variant="text"
            size="small"
            @click="handleConfigureAccount(service)"
          />
        </template>
      </v-list-item>

      <v-list-item v-if="servicesStore.services.length === 0">
        <v-list-item-title class="text-medium-emphasis">No accounts configured</v-list-item-title>
      </v-list-item>
    </v-list>

    <div class="mt-4">
      <v-btn
        prepend-icon="mdi-plus"
        variant="outlined"
        color="primary"
        @click="handleAddAccount"
      >
        Add Account
      </v-btn>
    </div>

    <!-- Add Account Dialog -->
    <AddAccountDialog
      v-model="showAddDialog"
      @saved="handleAccountSaved"
    />

    <!-- Edit Account Dialog -->
    <EditAccountDialog
      v-if="editService"
      v-model="showEditDialog"
      :service-provider="editService.provider"
      :service-identifier="editService.identifier"
      @saved="handleAccountSaved"
    />
  </div>
</template>
