<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="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">{{ $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 font12">
              <span class="fontbold">{{ $t('profile.bank_data.warning_title') }}</span>
              {{ $t('profile.bank_data.warning_message') }}
            </div>
          </div>



          <q-card class="q-pa-md bg-white shadow-card q-mb-md" style="border-radius: 20px;" :flat="false">
            <div class="text-center text-text q-mb-sm font14 fontbold">
              <div>
                {{ $t('profile.bank_data.pix_title') }}
              </div>
            </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"
              padding="4px 12px"
              :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-center text-text q-mb-sm col-12 font14 fontbold">
              {{ $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"
              :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.provider.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.provider.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.provider.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>
