<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-pa-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.address.title') }}</span>
        <q-space />
        <div style="width: 32px"></div>
      </div>
      <q-card-section class="col q-pa-lg">
        <div class="text-text">
          <div class="text-h6 text-weight-bold gradient-diarista">{{ $t('profile.address.address_subtitle') }}</div>
          <div class="text-caption text-grey-7 q-mb-lg">{{ $t('profile.address.address_description') }}</div>
 

          <q-card class="q-pa-lg bg-white shadow-card" style="border-radius: 25px;" :flat="false">
            <q-input
              v-model="search"
              outlined
              dense
              class="q-mb-md bg-white card-border"
              input-class="text-text"
              :placeholder="$t('profile.address.search_placeholder')"
            >
              <template #append>
                <q-icon name="mdi-magnify" color="grey-7"/>
              </template>
            </q-input>

            <div class="text-weight-bold text-text q-mb-xs">{{ $t('profile.address.cep') }}</div>
            <q-input
              v-model="form.zip_code"
              input-class="text-text"
              outlined
              dense
              mask="#####-###"
              unmasked-value
              placeholder="00000-000"
              class="q-mb-md"
              @update:model-value="onCepChange"
            >
              <template #append>
                <q-spinner v-if="loadingCep" size="xs" color="primary" />
              </template>
            </q-input>

            <div class="text-weight-bold q-mb-xs text-text">{{ $t('profile.address.address_label') }}</div>
            <q-input 
              v-model="form.address" 
              outlined 
              dense 
              class="q-mb-md" 
              input-class="text-text" 
              :placeholder="$t('profile.address.address_placeholder')"
            />

            <div class="row q-col-gutter-sm q-mb-md">
              <div class="col-4">
                <div class="text-weight-bold q-mb-xs text-text">{{ $t('profile.address.number') }}</div>
                <q-input v-model="form.number" outlined dense input-class="text-text" placeholder="0000"/>
              </div>
              <div class="col-8">
                <div class="text-weight-bold q-mb-xs text-text">{{ $t('profile.address.complement') }}</div>
                <q-input v-model="form.complement" outlined dense input-class="text-text" :placeholder="$t('profile.address.complement_placeholder')"/>
              </div>
            </div>

            <div class="text-weight-bold q-mb-xs text-text">{{ $t('profile.address.district_label') }}</div>
            <q-input v-model="form.district" outlined dense class="q-mb-md" input-class="text-text"/>

            <div class="row q-col-gutter-sm q-mb-lg">
              <div class="col-8">
                <div class="text-weight-bold q-mb-xs text-text">{{ $t('profile.address.city_label') }}</div>
                <q-input :model-value="form.city?.name" readonly outlined dense input-class="text-text"/>
              </div>
              <div class="col-4">
                <div class="text-weight-bold q-mb-xs text-text">{{ $t('profile.address.state_label') }}</div>
                <q-input :model-value="form.state?.name" readonly outlined dense input-class="text-text"/>
              </div>
            </div>

            <q-btn
              unelevated
              rounded
              no-caps
              color="primary"
              class="full-width q-py-md text-weight-bold"
              padding="8px 16px"
              style="font-size: 1.1rem;"
              :label="$t('profile.address.update_address')"
              :loading="saving"
              :disable="!hasUpdatedFields"
              @click="save"
            />
          </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 { searchAddressByCEP, updateAddress, createAddress, getAddresses } from 'src/api/address';
import { userStore } from 'src/stores/user';
import { useFormUpdateTracker } from 'src/composables/useFormUpdateTracker';

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

const { dialogRef, onDialogOK } = useDialogPluginComponent();
const $q = useQuasar();
const user = userStore();
const providerId = user.user.provider.id;
const {
  form,
  hasUpdatedFields,
  getUpdatedFields,
  setUpdateFormAsOriginal,
} = useFormUpdateTracker({
  zip_code: '',
  address: '',
  number: '',
  complement: '',
  district: '',
  city_id: null,
  state_id: null,
  city: null,
  state: null,
  source: 'provider',
  source_id: providerId,
  address_type: 'home',
});

const search = ref('');
const loadingCep = ref(false);
const saving = ref(false);
const addressId = ref(null);

const onCepChange = async (val) => {
  if (val?.length === 8) {
    loadingCep.value = true;
    try {
      const data = await searchAddressByCEP(val);
      if (data) {
        form.address = data.address;
        form.district = data.district;
        form.city_id = data.city_id;
        form.state_id = data.state_id;
        form.city = data.city;
        form.state = data.state;
      } else {
        $q.notify({ type: 'negative', message: 'CEP não encontrado' });
      }
    } finally {
      loadingCep.value = false;
    }
  }
};

const save = async () => {
  saving.value = true;
  try {
    let response;
    if (addressId.value) {
      response = await updateAddress(getUpdatedFields.value, addressId.value);
    } else {
      response = await createAddress({ ...form });
    }

    if (response) {
      setUpdateFormAsOriginal();
      onDialogOK(response);
    }
  } catch (error) {
    console.error('Erro ao salvar endereço:', error);
  } finally {
    saving.value = false;
  }
};

onMounted(async () => {
  const providersAddresses = await getAddresses('provider', providerId);
  if (providersAddresses && providersAddresses.length > 0) {
    const current = providersAddresses[0];
    addressId.value = current.id;
    const initialData = {
      zip_code: current.zip_code || '',
      address: current.address || '',
      number: current.number || '',
      complement: current.complement || '',
      district: current.district || '',
      city_id: current.city_id || null,
      state_id: current.state_id || null,
      city: current.city || null,
      state: current.state || null,
      source: 'provider',
      source_id: providerId,
      address_type: current.address_type || 'home',
    };

    Object.assign(form, initialData);
    setUpdateFormAsOriginal();
  }
});
</script>

<style scoped>
</style>
