<template>
  <q-card-section class="no-padding">
    <div class="text-text">
      <span class="text-weight-medium">{{ $t('provider.login.steps.step_3.full_name') }}</span>
    </div>
    <q-input
      v-model="form.name"
      no-error-icon
      outlined
      rounded
      class="bg-surface q-mt-sm q-mb-md"
      input-class="text-text"
      :placeholder="$t('provider.login.steps.step_3.full_name')"
      hide-bottom-space
      :rules="[inputRules.required]"
      lazy-rules
    />

    <div class="text-text">
      <span class="text-weight-medium">{{ $t('common.terms.phone') }}</span>
    </div>
    <q-input
      v-model="form.phone"
      no-error-icon
      outlined
      rounded
      class="bg-surface q-mt-sm q-mb-md"
      input-class="text-text"
      placeholder="(00) 00000-0000"
      hide-bottom-space
      :rules="[inputRules.required]"
      lazy-rules
      mask="(##) #####-####"
    />

    <div class="text-text">
      <span class="text-weight-medium">{{ $t('common.terms.email') }}</span>
    </div>
    <q-input
      v-model="form.email"
      no-error-icon
      outlined
      rounded
      class="bg-surface q-mt-sm q-mb-md"
      input-class="text-text"
      placeholder="nome@email.com"
      hide-bottom-space
      readonly
      :rules="[inputRules.required, inputRules.email]"
      lazy-rules
      type="email"
    />

    <div class="text-text">
      <span class="text-weight-medium">{{ $t('provider.login.steps.step_3.rg') }}</span>
    </div>
    <q-input
      v-model="form.rg"
      no-error-icon
      outlined
      rounded
      class="bg-surface q-mt-sm q-mb-md"
      input-class="text-text"
      placeholder="00.000.000-0"
      hide-bottom-space
      :rules="[inputRules.required, validateRG]"
      lazy-rules
      mask="##.###.###-#"
    />

    <div class="text-text">
      <span class="text-weight-medium">{{ $t('common.terms.cpf') }}</span>
    </div>
    <q-input
      v-model="form.document"
      no-error-icon
      outlined
      rounded
      class="bg-surface q-mt-sm q-mb-md"
      input-class="text-text"
      placeholder="000.000.000-00"
      hide-bottom-space
      :rules="[inputRules.required, inputRules.cpf]"
      lazy-rules
      mask="###.###.###-##"
    />

    <div class="text-text">
      <span class="text-weight-medium">{{ $t('provider.login.steps.step_3.birth_date') }}</span>
    </div>
    <q-input
      v-model="form.birth_date"
      no-error-icon
      outlined
      rounded
      class="bg-surface q-mt-sm q-mb-md"
      input-class="text-text"
      :placeholder="$t('provider.login.steps.step_3.birth_date_placeholder')"
      hide-bottom-space
      :rules="[inputRules.required, validateBirthDate]"
      lazy-rules
      mask="##/##/####"
    />

    <div class="text-text">
      <span class="text-weight-medium">{{ $t('common.terms.cep') }}</span>
    </div>
    <q-input
      v-model="form.zip_code"
      no-error-icon
      outlined
      rounded
      class="bg-surface q-mt-sm q-mb-md"
      input-class="text-text"
      placeholder="00000-000"
      hide-bottom-space
      :rules="[inputRules.required, inputRules.cep]"
      lazy-rules
      mask="#####-###"
      :loading="loadingCep"
      @update:model-value="onCepChange"
    />

    <div class="text-text">
      <span class="text-weight-medium">{{ $t('common.terms.address') }}</span>
    </div>
    <q-input
      v-model="form.address"
      no-error-icon
      outlined
      rounded
      class="bg-surface q-mt-sm q-mb-md"
      input-class="text-text"
      :placeholder="$t('provider.login.steps.step_3.address_placeholder')"
      hide-bottom-space
      :rules="[inputRules.required]"
      lazy-rules
    />
    <div class="text-center">
      <q-checkbox
        v-model="form.no_complement"
        :label="$t('provider.login.steps.step_3.no_complement')"
        class="q-mb-md text-text"
        color="primary"
        keep-color
      />
    </div>

    <template v-if="!form.no_complement">
      <div class="text-text">
        <span class="text-weight-medium">{{ $t('common.terms.complement') }}</span>
      </div>
      <q-input
        v-model="form.complement"
        no-error-icon
        outlined
        rounded
        class="bg-surface q-mt-sm q-mb-md"
        input-class="text-text"
        :placeholder="$t('provider.login.steps.step_3.complement_placeholder')"
        hide-bottom-space
        :rules="[inputRules.required]"
        lazy-rules
      />
    </template>
  </q-card-section>
</template>

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

const { t } = useI18n();
const form = defineModel({ type: Object, required: true });
const { inputRules } = useInputRules();
const loadingCep = ref(false);

const validateRG = (value) => {
  const cleanedValue = value?.replace(/\D/g, '') || '';
  return cleanedValue.length >= 8 || t('provider.login.steps.step_3.rg_invalid');
};

const validateBirthDate = (value) => {
  if (!value) return t('validation.rules.required');

  const matches = /^(\d{2})\/(\d{2})\/(\d{4})$/.exec(value);
  if (!matches) return t('provider.login.steps.step_3.date_invalid');

  const day = Number(matches[1]);
  const month = Number(matches[2]);
  const year = Number(matches[3]);

  const date = new Date(year, month - 1, day);
  const isValidDate =
    date.getFullYear() === year &&
    date.getMonth() === month - 1 &&
    date.getDate() === day;

  if (!isValidDate) return t('provider.login.steps.step_3.date_invalid');
  if (date > new Date()) return t('provider.login.steps.step_3.date_invalid');

  return true;
};
// ...existing code...

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) {
      form.value.address = `${data.logradouro}, ${data.bairro} - ${data.localidade}/${data.uf}`;
      form.value.city = data.localidade;
      form.value.state = data.uf;
    } else {
      form.value.address = '';
      form.value.city = '';
      form.value.state = '';
    }
  } catch {
    form.value.address = '';
    form.value.city = '';
    form.value.state = '';
  } finally {
    loadingCep.value = false;
  }
};

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