<template>
  <div class="q-pa-md">
    <q-form ref="formRef">
      <div class="column justify-center items-center q-mb-lg">
        <AvatarImageComponent ref="avatarRef" @update:file="onAvatarChange" />

        <div class="row full-width q-mt-md q-col-gutter-sm">
          <DefaultInput
            :model-value="form.social_reason"
            class="col-12"
            disable
            label="Razão Social"
            outlined
          />

          <DefaultInput
            :model-value="form.fantasy_name"
            class="col-12"
            disable
            label="Nome Fantasia"
            outlined
          />

          <DefaultInput
            :model-value="form.cnpj"
            class="col-4"
            disable
            label="CNPJ"
            outlined
          />

          <DefaultInput
            :model-value="form.state_registration"
            class="col-4"
            disable
            label="Inscrição Estadual"
            outlined
          />

          <DefaultInput
            :model-value="form.name_responsible"
            class="col-4"
            disable
            label="Responsável"
            outlined
          />

          <DefaultInput
            :model-value="form.postal_code"
            class="col-3"
            disable
            label="CEP"
            outlined
          />

          <DefaultInput
            :model-value="form.street"
            class="col-6"
            disable
            label="Endereço"
            outlined
          />

          <DefaultInput
            :model-value="form.address_number"
            class="col-3"
            disable
            label="Número"
            outlined
          />

          <DefaultInput
            :model-value="form.neighborhood"
            class="col-4"
            disable
            label="Bairro"
            outlined
          />

          <DefaultInput
            :model-value="stateName"
            class="col-4"
            disable
            label="Estado"
            outlined
          />

          <DefaultInput
            :model-value="cityName"
            class="col-4"
            disable
            label="Cidade"
            outlined
          />

          <DefaultInput
            :model-value="form.complement"
            class="col-12"
            disable
            label="Complemento"
            outlined
          />

          <DefaultInput
            :model-value="form.email"
            class="col-6"
            disable
            label="E-mail Principal"
            outlined
          />

          <DefaultInput
            :model-value="form.secondary_email"
            class="col-6"
            disable
            label="E-mail Secundário"
            outlined
          />

          <DefaultInput
            :model-value="form.phone_number"
            class="col-6"
            disable
            label="Telefone"
            outlined
          />

          <DefaultInput
            :model-value="form.cell_number"
            class="col-6"
            disable
            label="Celular"
            outlined
          />

          <div class="col-12 q-mt-sm">
            <div class="text-subtitle2 text-grey-7 q-mb-sm">Alterar Senha</div>
          </div>

          <DefaultPasswordInput
            v-model="password"
            v-model:error="validationErrors.password"
            class="col-6"
            label="Nova Senha"
            outlined
            :rules="password ? [inputRules.password] : []"
          />

          <DefaultPasswordInput
            v-model="passwordConfirmation"
            v-model:error="validationErrors.password_confirmation"
            class="col-6"
            label="Confirmar Nova Senha"
            outlined
            :rules="password ? [inputRules.samePassword(password)] : []"
          />
        </div>

        <div class="row justify-end q-mt-md items-end full-width q-px-xs">
          <q-btn
            color="primary-2"
            label="Salvar"
            :disable="!hasChanges"
            :loading="loading"
            @click="onSave"
          />
        </div>
      </div>
    </q-form>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from "vue";
import { getUnitMe, updateUnitMe } from "src/api/unit";
import { updateUserMe } from "src/api/user.js";
import { useInputRules } from "src/composables/useInputRules";
import { useSubmitHandler } from "src/composables/useSubmitHandler";

import DefaultInput from "src/components/defaults/DefaultInput.vue";
import DefaultPasswordInput from "src/components/defaults/DefaultPasswordInput.vue";
import AvatarImageComponent from "src/components/shared/AvatarImageComponent.vue";

const props = defineProps({
  getFormAsFormData: { type: Function, required: true },
  setUpdateFormAsOriginal: { type: Function, required: true },
  unitId: { type: Number, default: null },
});

const form = defineModel("form", { type: Object, required: true });

const { inputRules } = useInputRules();

const avatarRef = ref(null);
const cityName = ref("");
const formRef = ref(null);
const newAvatarFile = ref(null);
const password = ref(null);
const passwordConfirmation = ref(null);
const stateName = ref("");

const hasChanges = computed(() => !!newAvatarFile.value || !!password.value);

const { loading, validationErrors, execute } = useSubmitHandler({ formRef });

function onAvatarChange(file) {
  newAvatarFile.value = file;
}

async function onSave() {
  await execute(async () => {
    if (newAvatarFile.value) {
      const formData = new FormData();

      formData.append("avatar", newAvatarFile.value);

      await updateUnitMe(formData);

      newAvatarFile.value = null;
    }

    if (password.value) {
      await updateUserMe({ password: password.value });

      password.value = null;

      passwordConfirmation.value = null;
    }
  });
}

onMounted(async () => {
  try {
    const unit = await getUnitMe();
    form.value.fantasy_name = unit.fantasy_name;
    form.value.social_reason = unit.social_reason;
    form.value.cnpj = unit.cnpj;
    form.value.state_registration = unit.state_registration;
    form.value.name_responsible = unit.name_responsible;
    form.value.street = unit.street;
    form.value.address_number = unit.address_number;
    form.value.postal_code = unit.postal_code;
    form.value.neighborhood = unit.neighborhood;
    form.value.complement = unit.complement;
    form.value.email = unit.email;
    form.value.secondary_email = unit.secondary_email;
    form.value.phone_number = unit.phone_number;
    form.value.cell_number = unit.cell_number;
    stateName.value = unit.state?.name ?? "";
    cityName.value = unit.city?.name ?? "";
    if (unit.avatar_url) {
      avatarRef.value?.setImageUrl(unit.avatar_url);
    }
    props.setUpdateFormAsOriginal();
  } catch (e) {
    console.error(e);
  }
});
</script>
