<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">
          {{ isEditing ? $t('profile.address.edit_address') : $t('profile.address.add_new_address') }}
        </span>
        <q-space />
        <div style="width: 32px"></div>
      </div>

      <q-card-section class="col">
        <div class="q-px-md q-pt-lg text-text">
          <q-card class="q-pa-lg bg-white shadow-card" style="border-radius: 25px;" :flat="false">
            <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>

            <div class="q-mb-lg">
              <div class="row q-gutter-sm">
                <q-chip
                  v-for="type in addressTypes"
                  :key="type.value"
                  :selected="form.address_type === type.value"
                  clickable
                  color="primary"
                  :outline="form.address_type !== type.value"
                  text-color="surface"
                  :icon="type.icon"
                  :icon-selected="type.icon"
                  @click="form.address_type = type.value"
                >
                  {{ $t(type.label) }}
                </q-chip>
              </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('common.actions.save')"
              :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 } from 'src/api/address';
import { userStore } from 'src/stores/user';
import { useFormUpdateTracker } from 'src/composables/useFormUpdateTracker';
import { useI18n } from 'vue-i18n';

const props = defineProps({
  isEditing: {
    type: Boolean,
    default: false,
  },
  addressData: {
    type: Object,
    default: null,
  },
});

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

const { dialogRef, onDialogOK } = useDialogPluginComponent();
const $q = useQuasar();
const { t } = useI18n();
const user = userStore();
const clientId = user.user.client.id;

const initialFormData = {
  zip_code: '',
  address: '',
  number: '',
  complement: '',
  district: '',
  city_id: null,
  state_id: null,
  city: null,
  state: null,
  source: 'client',
  source_id: clientId,
  address_type: 'home',
};

const { form, hasUpdatedFields, getUpdatedFields, setUpdateFormAsOriginal } =
  useFormUpdateTracker(initialFormData);

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

const addressTypes = [
  { value: 'home', label: 'profile.address.type.home', icon: 'mdi-home-outline' },
  { value: 'commercial', label: 'profile.address.type.commercial', icon: 'mdi-briefcase-variant-outline' },
  { value: 'other', label: 'profile.address.type.other', icon: 'mdi-map-marker-outline' },
];

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: t('profile.address.cep_not_found') });
      }
    } finally {
      loadingCep.value = false;
    }
  }
};

const save = async () => {
  saving.value = true;
  try {
    let response;
    if (props.isEditing && 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);
    $q.notify({ type: 'negative', message: t('profile.address.error_saving') });
  } finally {
    saving.value = false;
  }
};

onMounted(() => {
  if (props.isEditing && props.addressData) {
    addressId.value = props.addressData.id;

    const initialData = {
      zip_code: props.addressData.zip_code || '',
      address: props.addressData.address || '',
      number: props.addressData.number || '',
      complement: props.addressData.complement || '',
      district: props.addressData.district || '',
      city_id: props.addressData.city_id || null,
      state_id: props.addressData.state_id || null,
      city: props.addressData.city || null,
      state: props.addressData.state || null,
      source: 'client',
      source_id: clientId,
      address_type: props.addressData.address_type || 'home',
    };

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

<style scoped>
</style>
