<template>
  <div>
    <DefaultHeaderPage title="Integração Asaas" />

    <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 — Conta da Franqueadora</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">
          Informe aqui a chave da API da conta Asaas da franqueadora. Ela é usada para
          emitir as cobranças do TBR das unidades. Você pode trocá-la a qualquer momento —
          sem depender do suporte. Enquanto não houver chave, o sistema usa a configuração
          padrão do ambiente.
        </div>

        <q-form ref="formRef">
          <DefaultPasswordInput
            v-model="apiKey"
            v-model:error="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"
              label="Salvar"
              :disable="!apiKey"
              :loading="loading"
              @click="onSave"
            />
          </div>
        </q-form>
      </q-card>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { useSubmitHandler } from "src/composables/useSubmitHandler";
import {
  getCompanyPaymentAccount,
  saveCompanyPaymentAccount,
} from "src/api/company_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 formRef = ref(null);
const canEdit = permissionStore().getAccess("franchisor_financial", "edit");
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 getCompanyPaymentAccount();
    account.value = data ?? defaultAccount();
  } catch (e) {
    console.error(e);
  }
}

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

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

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

onMounted(fetchData);
</script>
