<script setup lang="ts">

const route = useRoute()
const toast = useToast()
const mode = route.params.mode
const isCreate = computed(() => mode === "create")
const loading = ref(false)

const itemInfo = ref({
  email: "",
  password: "",
  imapHost: "",
  imapPort: 993,
  imapSsl: true,
  smtpHost: "",
  smtpPort: 587,
  smtpSsl: false,
})

const setup = async () => {
  if(!isCreate.value) {
    const account = await useNuxtApp().$api(`/api/email/accounts/${route.params.id}`)
    itemInfo.value = {
      ...itemInfo.value,
      ...account,
      password: "",
    }
  }
}
setup()

const payload = () => ({
  ...itemInfo.value,
  imapPort: Number(itemInfo.value.imapPort),
  smtpPort: Number(itemInfo.value.smtpPort),
  password: itemInfo.value.password || undefined,
})

const createAccount = async () => {
  loading.value = true
  const res = await useNuxtApp().$api(`/api/email/accounts`, {
    method: "POST",
    body: payload(),
  })

  if(res.success) {
    toast.add({ title: "E-Mail Konto erstellt", color: "success" })
    navigateTo("/settings/emailaccounts")
  }
  loading.value = false
}

const saveAccount = async () => {
  loading.value = true
  const res = await useNuxtApp().$api(`/api/email/accounts/${route.params.id}`, {
    method: "POST",
    body: payload(),
  })

  if(res.success) {
    toast.add({ title: "E-Mail Konto gespeichert", color: "success" })
    navigateTo("/settings/emailaccounts")
  }
  loading.value = false

}

const syncAccount = async () => {
  loading.value = true
  try {
    const res = await useNuxtApp().$api(`/api/email/accounts/${route.params.id}/sync`, {
      method: "POST",
      body: { limit: 50 },
    })

    toast.add({
      title: "E-Mail Konto synchronisiert",
      description: `${res.synced?.[0]?.fetched || 0} neue Nachrichten geladen`,
      color: "success",
    })
  } catch (err: any) {
    toast.add({
      title: "Synchronisation fehlgeschlagen",
      description: err?.data?.error || err?.message || "Das Konto konnte nicht synchronisiert werden.",
      color: "error",
    })
  } finally {
    loading.value = false
  }
}

</script>

<template>
  <UDashboardNavbar :title="`E-Mail Konto ${isCreate ? 'erstellen' : 'bearbeiten'}`">
    <template #right>
      <UButton
          icon="i-heroicons-arrow-left"
          color="neutral"
          variant="ghost"
          @click="navigateTo('/settings/emailaccounts')"
      />
      <UButton
          v-if="!isCreate"
          icon="i-heroicons-arrow-path"
          color="neutral"
          variant="soft"
          :loading="loading"
          @click="syncAccount"
      >
        Synchronisieren
      </UButton>
      <UButton
        v-if="isCreate"
        icon="i-heroicons-plus"
        :loading="loading"
        :disabled="!itemInfo.email || !itemInfo.password || !itemInfo.imapHost || !itemInfo.smtpHost"
        @click="createAccount"
      >
        Erstellen
      </UButton>
      <UButton
        v-if="!isCreate"
        icon="i-heroicons-check"
        :loading="loading"
        :disabled="!itemInfo.email || !itemInfo.imapHost || !itemInfo.smtpHost"
        @click="saveAccount"
      >
        Speichern
      </UButton>
    </template>
  </UDashboardNavbar>

  <div class="mx-auto max-w-4xl p-4">
    <UAlert
        v-if="!isCreate"
        class="mb-4"
        color="neutral"
        variant="soft"
        icon="i-heroicons-lock-closed"
        title="Passwort bleibt geschützt"
        description="Das gespeicherte Passwort wird nicht angezeigt. Trage nur dann ein neues Passwort ein, wenn du es ändern möchtest."
    />

    <UForm class="grid gap-6">
      <section class="grid gap-4">
        <div>
          <h2 class="text-base font-semibold">Konto</h2>
          <p class="text-sm text-dimmed">Diese Adresse wird als Absender und für den IMAP-Zugriff genutzt.</p>
        </div>

        <div class="grid gap-4 md:grid-cols-2">
          <UFormField label="E-Mail Adresse">
            <UInput
                v-model="itemInfo.email"
                type="email"
                placeholder="name@example.com"
            />
          </UFormField>

          <UFormField :label="isCreate ? 'Passwort' : 'Neues Passwort'">
            <UInput
                v-model="itemInfo.password"
                type="password"
                :placeholder="isCreate ? '' : 'Unverändert lassen'"
            />
          </UFormField>
        </div>
      </section>

      <USeparator label="Posteingang" />

      <section class="grid gap-4 md:grid-cols-[1fr_140px_120px] md:items-end">
        <UFormField label="IMAP Host">
          <UInput
              v-model="itemInfo.imapHost"
              placeholder="imap.example.com"
          />
        </UFormField>

        <UFormField label="Port">
          <UInput
              v-model="itemInfo.imapPort"
              type="number"
          />
        </UFormField>

        <UFormField label="SSL">
          <USwitch
              v-model="itemInfo.imapSsl"
          />
        </UFormField>
      </section>

      <USeparator label="Versand" />

      <section class="grid gap-4 md:grid-cols-[1fr_140px_120px] md:items-end">
        <UFormField label="SMTP Host">
          <UInput
              v-model="itemInfo.smtpHost"
              placeholder="smtp.example.com"
          />
        </UFormField>

        <UFormField label="Port">
          <UInput
              v-model="itemInfo.smtpPort"
              type="number"
          />
        </UFormField>

        <UFormField label="SSL">
          <USwitch
              v-model="itemInfo.smtpSsl"
          />
        </UFormField>
      </section>
    </UForm>
  </div>
</template>

<style scoped>

</style>
