<template>
  <q-dialog
    ref="dialogRef"
    maximized
    persistent
    transition-hide="slide-right"
    transition-show="slide-left"
  >
    <div class="bg-page full-height no-shadow">
      <div class="row items-center q-px-md q-pb-sm bg-white shadow-profile bg-surface dialog-safe-header">
        <q-btn
          v-close-popup
          color="primary"
          dense
          flat
          icon="mdi-chevron-left"
          round
        />

        <q-space />

        <span class="gradient-diarista font16 fontbold">
          {{ $t('profile.bank_data.title') }}
        </span>

        <q-space />

        <div style="width: 32px"></div>
      </div>

      <q-card-section class="col">
        <div class="text-text">
          <div class="gradient-diarista font14 fontbold">
            {{ $t('profile.bank_data.my_bank_data_title') }}
          </div>

          <div class="text-grey-7 q-mb-md font12 fontregular">
            {{ accounts.length ? $t('profile.bank_data.subtitle_manage') : $t('profile.bank_data.subtitle') }}
          </div>

          <div
            v-if="!showForm"
            class="column items-center q-mb-lg cursor-pointer new-account"
            @click="openCreateForm"
          >
            <q-btn
              class="new-account-btn shadow-card"
              color="white"
              icon="mdi-plus"
              round
              size="lg"
              text-color="primary"
              unelevated
            />

            <span class="font12 fontregular text-text q-mt-sm">
              {{ $t('profile.bank_data.new_account') }}
            </span>
          </div>

          <BankAccountForm
            v-if="showForm"
            :account="editingAccount"
            @cancel="closeForm"
            @saved="onSaved"
          />

          <div
            v-if="loading"
            class="row justify-center q-py-lg"
          >
            <q-spinner color="primary" size="32px" />
          </div>

          <q-card
            v-for="account in accounts"
            :key="account.id"
            class="q-pa-md bg-white shadow-card q-mb-md row items-center no-wrap account-card"
            :class="{ 'account-card--primary': account.is_primary }"
            style="border-radius: 20px;"
            :flat="false"
          >
            <div class="relative-position q-mr-md">
              <q-avatar
                class="bg-white shadow-card"
                size="44px"
                text-color="primary"
              >
                <q-icon name="mdi-currency-usd" />
              </q-avatar>

              <q-icon
                v-if="account.is_primary"
                class="account-card__check"
                color="primary"
                name="mdi-check-circle"
                size="16px"
              />
            </div>

            <div class="col">
              <div class="font14 fontbold text-text">
                {{ account.bank_name || account.bank_code }}
              </div>

              <div class="font12 fontregular text-grey-7">
                {{ account.holder_name }}
              </div>

              <div class="font12 fontregular text-grey-7">
                {{ $t('profile.bank_data.agency') }} {{ formatBranch(account) }}
              </div>

              <div class="font12 fontregular text-grey-7">
                {{ $t('profile.bank_data.account') }} {{ formatAccount(account) }}
              </div>

              <q-badge
                v-if="account.is_primary"
                class="q-mt-xs"
                color="primary"
                :label="$t('profile.bank_data.primary_badge')"
              />
            </div>

            <div class="column items-center">
              <q-btn
                color="grey-7"
                dense
                flat
                icon="mdi-pencil-outline"
                round
                size="sm"
                @click.stop="openEditForm(account)"
              />

              <q-btn
                v-if="canDelete(account)"
                color="grey-7"
                dense
                flat
                icon="mdi-trash-can-outline"
                round
                size="sm"
                @click.stop="confirmDelete(account)"
              />
            </div>
          </q-card>
        </div>

        <div class="q-pb-xl"></div>
      </q-card-section>
    </div>
  </q-dialog>
</template>

<script setup>
import BankAccountForm from 'src/components/profile/BankAccountForm.vue';
import { onMounted, ref } from 'vue';
import { deleteProviderBankAccount, getProviderBankAccounts } from 'src/api/providerBankAccount';
import { useDialogPluginComponent, useQuasar } from 'quasar';
import { useI18n } from 'vue-i18n';
import { userStore } from 'src/stores/user';

defineEmits([...useDialogPluginComponent.emits]);

const { dialogRef } = useDialogPluginComponent();
const { t } = useI18n();
const $q = useQuasar();
const user = userStore();

const accounts = ref([]);
const editingAccount = ref(null);
const loading = ref(false);
const showForm = ref(false);

const canDelete = (account) => !account.is_primary && accounts.value.length > 1;

const formatBranch = (account) =>
  [account.branch_number, account.branch_check_digit].filter(Boolean).join('-');

const formatAccount = (account) =>
  [account.account_number, account.account_check_digit].filter(Boolean).join('-');

const openCreateForm = () => {
  editingAccount.value = null;
  showForm.value = true;
};

const openEditForm = (account) => {
  editingAccount.value = account;
  showForm.value = true;
};

const closeForm = () => {
  editingAccount.value = null;
  showForm.value = false;
};

const onSaved = async () => {
  closeForm();

  await loadAccounts();

  await user.fetchUser();
};

const confirmDelete = (account) => {
  $q.dialog({
    title: t('profile.bank_data.delete_title'),
    message: t('profile.bank_data.delete_message'),
    cancel: { flat: true, label: t('profile.bank_data.cancel'), noCaps: true },
    ok: { color: 'negative', label: t('profile.bank_data.confirm'), noCaps: true, rounded: true, unelevated: true },
    persistent: true,
  }).onOk(() => removeAccount(account));
};

const removeAccount = async (account) => {
  loading.value = true;

  try {
    await deleteProviderBankAccount(account.id);

    await loadAccounts();

    await user.fetchUser();
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
};

//

const loadAccounts = async () => {
  loading.value = true;

  try {
    accounts.value = await getProviderBankAccounts();
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
};

onMounted(loadAccounts);
</script>

<style scoped>
.account-card--primary {
  border: 1px solid var(--q-primary);
}

.account-card__check {
  position: absolute;
  top: -2px;
  right: -2px;
  background: #FFFFFF;
  border-radius: 50%;
}

.new-account {
  width: fit-content;
}

.new-account-btn {
  border-radius: 50%;
}
</style>
