<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-pb-sm bg-white shadow-profile bg-surface dialog-safe-header">
        <q-btn v-close-popup icon="mdi-chevron-left" flat round dense color="primary" />
        <q-space />
        <span class="font16 fontbold gradient-diarista">{{ $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="gradient-diarista font16 fontbold">{{ $t('profile.address.address_subtitle') }}</div>
          <div class="text-grey-7 q-mb-lg font12">{{ $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-text q-mb-xs font14 fontbold">{{ $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="q-mb-xs text-text font14 fontbold">{{ $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="q-mb-xs text-text font14 fontbold">{{ $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="q-mb-xs text-text font14 fontbold">{{ $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="q-mb-xs text-text font14 fontbold">{{ $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="q-mb-xs text-text font14 fontbold">{{ $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="q-mb-xs text-text font14 fontbold">{{ $t('profile.address.state_label') }}</div>
                <q-input :model-value="form.state?.name" readonly outlined dense input-class="text-text"/>
              </div>
            </div>

            <div v-if="missingCoords" class="q-mb-md">
              <q-banner rounded dense class="bg-orange-1 text-warning q-mb-sm">
                <template #avatar>
                  <q-icon name="mdi-map-marker-off" color="orange-7" />
                </template>
                {{ $t('profile.address.missing_coords') }}
              </q-banner>
              <q-btn
                unelevated
                rounded
                no-caps
                outline
                color="primary"
                icon="mdi-map-marker"
                class="full-width q-mb-md"
                :label="$t('profile.address.update_on_map')"
                :loading="geocodingCep"
                @click="openMapDialog"
              />
            </div>

            <q-btn
              unelevated
              rounded
              no-caps
              color="primary"
              class="full-width q-py-md"
              padding="8px 16px"
              :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, computed, 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';
import { useGeocodingApi } from 'src/composables/useGeocodingApi';
import LocationMapDialog from 'src/components/shared/LocationMapDialog.vue';

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

const { dialogRef, onDialogOK } = useDialogPluginComponent();
const $q = useQuasar();
const user = userStore();
const providerId = user.user.provider.id;
const { geocodeFullAddress } = useGeocodingApi();
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',
  latitude: null,
  longitude: null,
});

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

const missingCoords = computed(() =>
  addressId.value !== null && form.latitude == null && form.longitude == 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;
        form.latitude = null;
        form.longitude = null;
      } else {
        $q.notify({ type: 'negative', message: 'CEP não encontrado' });
      }
    } finally {
      loadingCep.value = false;
    }
  }
};

const openMapDialog = async () => {
  let initialLat = null;
  let initialLng = null;

  const hasAddress = form.address || form.zip_code;

  if (hasAddress) {
    geocodingCep.value = true;
    try {
      const geo = await geocodeFullAddress({
        address:  form.address,
        number:   form.number,
        district: form.district,
        zip_code: form.zip_code,
        city:     form.city?.name,
        state:    form.state?.name,
      });
      if (geo) {
        initialLat = geo.lat;
        initialLng = geo.lng;
      }
    } catch (err) {
      console.error('geocodeFullAddress falhou, usando coordenada default:', err);
    } finally {
      geocodingCep.value = false;
    }
  }

  const dialogProps = initialLat !== null
    ? { initialLat, initialLng }
    : {};

  $q.dialog({
    component: LocationMapDialog,
    componentProps: dialogProps,
  }).onOk(async (geoData) => {
    form.latitude = geoData.lat;
    form.longitude = geoData.lng;
    form.address = geoData.address || form.address;
    form.number = geoData.number || form.number;
    form.district = geoData.district || form.district;

    if (geoData.zip_code) {
      form.zip_code = geoData.zip_code.replace(/\D/g, '');
      try {
        const addressData = await searchAddressByCEP(form.zip_code);
        if (addressData) {
          form.city_id = addressData.city_id;
          form.state_id = addressData.state_id;
          form.city = addressData.city;
          form.state = addressData.state;
        }
      } catch {
        // mantém cidade/estado atual se lookup falhar
      }
    }
  });
};

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',
      latitude: current.latitude ?? null,
      longitude: current.longitude ?? null,
    };

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

<style scoped>
</style>
