<template>
  <q-dialog ref="dialogRef" persistent maximized transition-show="slide-left" transition-hide="slide-right">
    <div class="bg-page full-height no-shadow">
      <div class="row items-center q-px-md q-pt-md q-pb-sm bg-white shadow-profile bg-surface">
        <q-btn v-close-popup icon="mdi-chevron-left" flat round dense color="primary" />
        <q-space />
        <span class="text-subtitle1 text-weight-bold text-primary">{{ $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="text-h6 text-weight-bold gradient-diarista">{{ $t('profile.bank_data.my_bank_data_title') }}</div>
          <div class="text-caption text-grey-7 q-mb-md">{{ $t('profile.bank_data.subtitle') }}</div>

          <div class="pix-warning q-pa-md q-mb-md row items-start q-col-gutter-sm">
            <q-icon name="mdi-alert-outline" color="warning" size="20px" class="q-mt-xs" />
            <div class="col text-caption">
              <span class="text-weight-bold">{{ $t('profile.bank_data.warning_title') }}</span>
              {{ $t('profile.bank_data.warning_message') }}
            </div>
          </div>

          <div class="text-subtitle1 text-weight-bold text-center text-text q-mb-sm">
            {{ $t('profile.bank_data.pix_title') }}
          </div>

          <q-card class="q-pa-md bg-white shadow-card q-mb-md" style="border-radius: 20px;" :flat="false">
            <div class="text-weight-bold q-mb-xs text-text">{{ $t('profile.bank_data.pix_key') }}</div>
            <q-input
              v-model="pixForm.pix_key"
              outlined
              dense
              input-class="text-text"
              :placeholder="$t('profile.bank_data.pix_key_placeholder')"
              class="q-mb-sm"
            />

            <q-btn
              unelevated
              rounded
              no-caps
              color="primary"
              class="full-width text-weight-bold"
              padding="8px 16px"
              :label="pixAlreadyRegistered ? $t('profile.bank_data.att_pix') : $t('profile.bank_data.save_pix')"
              :loading="savingPix"
              :disable="!hasPixUpdatedFields"
              @click="savePix"
            />
          </q-card>


          <q-card class="q-pa-md bg-white row shadow-card q-mb-md" style="border-radius: 20px;" :flat="false">
            <div class="text-subtitle1 text-weight-bold text-center text-text q-mb-sm col-12">
              {{ $t('profile.bank_data.bank_account_title') }}
            </div>
            <div class="row q-mb-sm q-my-auto col-12 row items-center">
              <q-radio
                v-model="bankForm.bank_account_type"
                val="checking"
                :label="$t('profile.bank_data.checking')"
                color="primary"
                keep-color
                class="q-mr-lg text-text"
              />
              <q-radio
                v-model="bankForm.bank_account_type"
                val="savings"
                :label="$t('profile.bank_data.savings')"
                color="primary"
                keep-color
                class="text-text"
              />
            </div>

            <q-input
              v-model="bankForm.agency"
              outlined
              dense
              input-class="text-text"
              :placeholder="$t('profile.bank_data.agency')"
              class="q-mb-sm col-12"
            />

            <q-input
              v-model="bankForm.account"
              outlined
              dense
              input-class="text-text"
              :placeholder="$t('profile.bank_data.account')"
              class="q-mb-sm col-12"
            />

            <q-input
              v-model="bankForm.digit"
              outlined
              dense
              input-class="text-text"
              :placeholder="$t('profile.bank_data.digit')"
              class="q-mb-sm col-3"
            />

            <q-btn
              unelevated
              rounded
              no-caps
              color="primary"
              padding="8px 16px"
              class="full-width text-weight-bold"
              :label="bankAlreadyRegistered ? $t('profile.bank_data.att_bank') : $t('profile.bank_data.save_account')"
              :loading="savingBank"
              :disable="!hasBankUpdatedFields"
              @click="saveBank"
            />
          </q-card>
        </div>
        <div class="q-pb-xl"></div>
      </q-card-section>
    </div>
  </q-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useDialogPluginComponent, useQuasar } from 'quasar';
import {
  getProviderPaymentMethods,
  createProviderPaymentMethod,
  updateProviderPaymentMethod,
} from 'src/api/providerPaymentMethod';
import { userStore } from 'src/stores/user';
import { useFormUpdateTracker } from 'src/composables/useFormUpdateTracker';
import { useI18n } from 'vue-i18n';

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

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

const pixId = ref(null);
const bankId = ref(null);
const savingPix = ref(false);
const savingBank = ref(false);
const pixAlreadyRegistered = ref(false);
const bankAlreadyRegistered = ref(false);
const {
  form: pixForm,
  hasUpdatedFields: hasPixUpdatedFields,
  getUpdatedFields: getPixUpdatedFields,
  setUpdateFormAsOriginal: setPixOriginal,
} = useFormUpdateTracker({
  pix_key: '',
});

const {
  form: bankForm,
  hasUpdatedFields: hasBankUpdatedFields,
  getUpdatedFields: getBankUpdatedFields,
  setUpdateFormAsOriginal: setBankOriginal,
} = useFormUpdateTracker({
  bank_account_type: 'checking',
  agency: '',
  account: '',
  digit: '',
});

const savePix = async () => {
  if (!pixForm.pix_key) {
    $q.notify({ type: 'negative', message: t('profile.bank_data.pix_key_required') });
    return;
  }

  savingPix.value = true;
  try {
    const payload = {
      provider_id: user.user.id,
      account_type: 'pix',
      pix_key: pixForm.pix_key,
    };

    if (pixId.value) {
      await updateProviderPaymentMethod(pixId.value, getPixUpdatedFields.value);
    } else {
      const created = await createProviderPaymentMethod(payload);
      pixId.value = created.id;
    }

    setPixOriginal();
    $q.notify({ type: 'positive', message: t('profile.bank_data.pix_saved') });
  } catch (error) {
    $q.notify({ type: 'negative', message: t('profile.bank_data.save_error') });
    console.log(error);
  } finally {
    savingPix.value = false;
  }
};

const saveBank = async () => {
  if (!bankForm.agency || !bankForm.account) {
    $q.notify({ type: 'negative', message: t('profile.bank_data.bank_fields_required') });
    return;
  }

  savingBank.value = true;
  try {
    const payload = {
      provider_id: user.user.id,
      account_type: 'bank_account',
      bank_account_type: bankForm.bank_account_type,
      agency: bankForm.agency,
      account: bankForm.account,
      digit: bankForm.digit,
    };

    if (bankId.value) {
      await updateProviderPaymentMethod(bankId.value, getBankUpdatedFields.value);
    } else {
      const created = await createProviderPaymentMethod(payload);
      bankId.value = created.id;
    }

    setBankOriginal();
    $q.notify({ type: 'positive', message: t('profile.bank_data.account_saved') });
  } catch (error) {
    $q.notify({ type: 'negative', message: t('profile.bank_data.save_error') });
    console.log(error);
  } finally {
    savingBank.value = false;
  }
};

onMounted(async () => {
  try {
    const methods = await getProviderPaymentMethods(user.user.id);
    if (!methods) return;

    const pix = methods.find((m) => m.account_type === 'pix');
    if (pix) {
      pixId.value = pix.id;
      pixForm.pix_key = pix.pix_key || '';
      setPixOriginal();
      pixAlreadyRegistered.value = true;
    }

    const bank = methods.find((m) => m.account_type === 'bank_account');
    if (bank) {
      bankId.value = bank.id;
      bankForm.bank_account_type = bank.bank_account_type || 'checking';
      bankForm.agency = bank.agency || '';
      bankForm.account = bank.account || '';
      bankForm.digit = bank.digit || '';
      setBankOriginal();
      bankAlreadyRegistered.value = true;
    }
  } catch (error) {
    console.error('Erro ao carregar dados bancários:', error);
  }
});
</script>

<style scoped>
.pix-warning {
  background-color: #EEF0FF;
  border-radius: 12px;
}
</style>
