<template>
  <div class="column col-12">
    <q-card class="step4-card col-12">
      <div class="bg-surface q-pa-lg">
        <div class="text-center q-mb-md">
          <div class="text-primary text-weight-bold">
            {{ $t('auth.step4_title') }}
          </div>
        </div>

        <q-input
          v-model="cep"
          no-error-icon
          outlined
          rounded
          class="bg-surface q-mb-md"
          input-class="text-text"
          placeholder="Digite seu CEP"
          hide-bottom-space
          :rules="[inputRules.requiredHideMessage, inputRules.cep]"
          lazy-rules
          mask="#####-###"
          :loading="loadingCep"
          :bottom-slots="false"
          @update:model-value="onCepChange"
        >
          <template #prepend>
            <q-icon name="mdi-map-marker-outline" color="grey-5" class="q-mr-sm" />
          </template>
        </q-input>

        <q-btn
          color="primary-button"
          :label="$t('auth.use_location')"
          rounded
          padding="6px 16px"
          class="full-width"
          @click="useLocation"
        />

      </div>
    </q-card>
    <div class="text-center q-pt-sm">
      <q-btn
        flat
        rounded
        color="surface"
        :label="$t('auth.back_to_register')"
        :icon="'mdi-chevron-left-circle-outline'"
        @click="emit('back')"
      />
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useInputRules } from 'src/composables/useInputRules';
import axios from 'axios';

const emit = defineEmits(['back']);
const cep = defineModel('cep', { type: String, default: '' });

const { inputRules } = useInputRules();
const loadingCep = ref(false);

const fetchCep = async (rawCep) => {
  const cleaned = rawCep.replace(/\D/g, '');
  if (cleaned.length !== 8) return;
  loadingCep.value = true;
  try {
    const { data } = await axios.get(`https://viacep.com.br/ws/${cleaned}/json/`);
    if (data.erro) cep.value = '';
  } catch (error) {
    console.log(error)
  } finally {
    loadingCep.value = false;
  }
};

const onCepChange = (val) => {
  const cleaned = val?.replace(/\D/g, '') ?? '';
  if (cleaned.length === 8) fetchCep(val);
};

const useLocation = () => {
  // getlocationfromdevice
};
</script>

<style lang="scss" scoped>
.step4-card {
  width: 100%;
  max-width: 340px;
  border-radius: 30px;
  position: relative;
  z-index: 1;
}
</style>
