<template>
  <q-form ref="formEnderecoRef" @submit="saveEndereco">
    <q-card flat class="cadastro-card q-pa-md">
      <div v-if="loading" class="flex flex-center q-pa-xl">
        <q-spinner color="violet-normal" size="40px" />
      </div>

      <div v-else class="row q-col-gutter-sm">
        <DefaultInput
          v-model="formEndereco.zip_code"
          v-model:error="errorsEndereco.zip_code"
          :label="$t('parceiro.zip_code')"
          :placeholder="'00000-000'"
          :mask="'#####-###'"
          class="col-md-4 col-12"
          @update:model-value="onCepChange"
        />
        <DefaultInput
          v-model="formEndereco.address"
          v-model:error="errorsEndereco.address"
          :label="$t('parceiro.address')"
          :loading="loadingCep"
          class="col-md-8 col-12"
        />
        <DefaultInput
          v-model="formEndereco.neighborhood"
          v-model:error="errorsEndereco.neighborhood"
          :label="$t('parceiro.neighborhood')"
          :loading="loadingCep"
          class="col-12"
        />
        <StateSelect
          v-model="selectedState"
          v-model:error="errorsEndereco.state_id"
          class="col-md-4 col-12 input-violet"
        />
        <CitySelect
          v-model="selectedCity"
          v-model:error="errorsEndereco.city_id"
          :state="selectedState"
          class="col-md-8 col-12 input-violet"
        />
      </div>
    </q-card>

    <div class="row justify-end q-pt-md bg-violet-light">
      <q-btn
        unelevated
        class="btn-gradient"
        :label="$t('common.actions.save')"
        icon="mdi-check"
        type="submit"
        :loading="loadingEndereco"
        :disable="!hasUpdatedEndereco"
      />
    </div>
  </q-form>
</template>

<script setup>
import { ref, watch } from "vue";
import { useQuasar } from "quasar";
import { useI18n } from "vue-i18n";
import { useFormUpdateTracker } from "src/composables/useFormUpdateTracker";
import { useSubmitHandler } from "src/composables/useSubmitHandler";
import { getPartnerAgreementEndereco, updatePartnerAgreement } from "src/api/partnerAgreement";
import { getCepData } from "src/api/cep";

import DefaultInput from "src/components/defaults/DefaultInput.vue";
import StateSelect from "src/components/selects/StateSelect.vue";
import CitySelect from "src/components/selects/CitySelect.vue";

const props = defineProps({
  partnerId: { type: Number, required: true },
  active:    { type: Boolean, default: false },
});

const emit = defineEmits(["partner-saved"]);

const $q = useQuasar();
const { t } = useI18n();

const formEnderecoRef = ref(null);

const selectedState = ref(null);
const selectedCity  = ref(null);
const loadingCep    = ref(false);
const loading       = ref(false);
const loaded        = ref(false);

const {
  form: formEndereco,
  getUpdatedFields: updatedEndereco,
  hasUpdatedFields: hasUpdatedEndereco,
} = useFormUpdateTracker({
  zip_code:     "",
  address:      "",
  neighborhood: "",
  city_id:      null,
  state_id:     null,
});

const {
  loading: loadingEndereco,
  validationErrors: errorsEndereco,
  execute: execEndereco,
} = useSubmitHandler({ formRef: formEnderecoRef });

const populate = (p) => {
  formEndereco.zip_code     = p.zip_code     ?? "";
  formEndereco.address      = p.address      ?? "";
  formEndereco.neighborhood = p.neighborhood ?? "";
  formEndereco.state_id     = p.state_id     ?? null;
  formEndereco.city_id      = p.city_id      ?? null;

  selectedState.value = p.state
    ? { label: p.state.name, value: p.state.id, code: p.state.code, country_id: p.state.country_id }
    : null;
  selectedCity.value = p.city
    ? { label: p.city.name, value: p.city.id, state_id: p.city.state_id }
    : null;
  // setUdateFormAsOriginal();
};

const loadData = async () => {
  loading.value = true;
  try {
    const p = await getPartnerAgreementEndereco(props.partnerId);
    populate(p);
    loaded.value = true;
  } catch {
    $q.notify({ type: "negative", message: t("http.errors.failed") });
  } finally {
    loading.value = false;
  }
};

const onCepChange = async (val) => {
  const digits = (val ?? "").replace(/\D/g, "");
  if (digits.length !== 8) return;
  loadingCep.value = true;
  try {
    const result = await getCepData(digits);

    if (result.address)      formEndereco.address      = result.address;
    if (result.neighborhood) formEndereco.neighborhood = result.neighborhood;

    if (result.city) {
      selectedCity.value = { label: result.city.name, value: result.city.id, state_id: result.state?.id };
      formEndereco.city_id = result.city.id;
    }

    if (result.state) {
      selectedState.value = { label: result.state.name, value: result.state.id };
      formEndereco.state_id = result.state.id;
    }
  } catch {
    console.log('error fetching cep')
  } finally {
    loadingCep.value = false;
  }
};

const saveEndereco = async () => {
  await execEndereco(async () => {
    const saved = await updatePartnerAgreement(props.partnerId, updatedEndereco.value);
    await populate(saved);
    emit("partner-saved", saved);
    $q.notify({ type: "positive", message: t("http.success") });
  });
};

watch(() => props.active, (isActive) => {
  if (isActive && !loaded.value) loadData();
}, { immediate: true });

watch(selectedState, (val) => { formEndereco.state_id = val?.value ?? null; });

watch(selectedCity,  (val) => { formEndereco.city_id  = val?.value ?? null; });
</script>

<style lang="scss" scoped>
.cadastro-card {
  border-radius: 12px;
  background: white;
}

.btn-gradient {
  background: linear-gradient(90deg, #4d1658 0%, #8b30a5 100%) !important;
  color: white !important;
  border-radius: 8px !important;
  padding: 8px 16px;
}

.btn-gradient :deep(.q-icon) {
  color: white !important;
}
</style>
