<template>
  <div>
    <DefaultHeaderPage title="APIs" />

    <div class="q-pa-md">
      <q-card flat bordered class="q-pa-md" style="max-width: 720px">
        <div class="row items-center no-wrap q-mb-xs">
          <q-icon name="mdi-cash-multiple" size="sm" color="primary" class="q-mr-sm" />
          <div class="text-subtitle1 text-weight-medium">Asaas</div>
          <q-space />
          <q-badge
            :color="account.asaas_configured ? 'positive' : 'grey-6'"
            :label="account.asaas_configured ? 'Configurada' : 'Não configurada'"
            class="q-px-sm q-py-xs"
          />
        </div>

        <div class="text-body2 text-grey-7 q-mb-md">
          Caso esta unidade possua conta própria no Asaas, informe aqui a chave da API
          para que as cobranças dos alunos sejam emitidas por ela. Este passo é
          <span class="text-weight-medium">opcional</span> — sem a chave, nenhuma
          cobrança é gerada pelo Asaas.
        </div>

        <DefaultForm ref="formRef">
          <DefaultPasswordInput
            v-model="apiKey"
            :error="!!validationErrors.asaas_api_key"
            :error-message="validationErrors.asaas_api_key"
            :label="
              account.asaas_configured
                ? 'Nova chave da API (deixe em branco para manter a atual)'
                : 'Chave da API do Asaas'
            "
            :placeholder="account.asaas_api_key_masked || ''"
            outlined
            autocomplete="off"
          />

          <div class="row justify-end items-center q-mt-md" style="gap: 12px">
            <q-btn
              v-if="canEdit && account.asaas_configured"
              flat
              color="negative"
              label="Remover chave"
              :disable="loading"
              @click="onRemove"
            />
            <q-btn
              v-if="canEdit"
              color="primary-2"
              label="Salvar"
              :disable="!apiKey"
              :loading="loading"
              @click="onSave"
            />
          </div>
        </DefaultForm>
      </q-card>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from "vue";
import { useSubmitHandler } from "src/composables/useSubmitHandler";
import {
  getPaymentAccountMe,
  savePaymentAccountMe,
} from "src/api/unit_payment_account";

import DefaultHeaderPage from "src/components/layout/DefaultHeaderPage.vue";
import DefaultPasswordInput from "src/components/defaults/DefaultPasswordInput.vue";
import { permissionStore } from "src/stores/permission";

const permissions = permissionStore();
const canEdit = computed(() =>
  permissions.getAccess("franchisee_integrations", "edit"),
);

const formRef = ref(null);
const apiKey = ref("");

const defaultAccount = () => ({
  asaas_configured: false,
  asaas_api_key_masked: null,
  status: "pending",
});

const account = ref(defaultAccount());

const { loading, validationErrors, execute } = useSubmitHandler({ formRef });

async function fetchData() {
  try {
    const data = await getPaymentAccountMe();
    account.value = data ?? defaultAccount();
  } catch (e) {
    console.error(e);
  }
}

async function persist(value) {
  await execute(async () => {
    account.value = await savePaymentAccountMe({ asaas_api_key: value });
    apiKey.value = "";
  });
}

function onSave() {
  if (!apiKey.value) return;
  persist(apiKey.value);
}

function onRemove() {
  persist("");
}

onMounted(fetchData);
</script>
