<template>
  <div class="q-pa-md">
    <DefaultForm
      ref="formRef"
      @submit="onSave"
    >
      <q-scroll-area
        ref="scrollAreaRef"
        class="unit-data-scroll-area"
      >
        <div class="column justify-center items-center q-pr-sm">
          <AvatarImageComponent
            ref="avatarRef"
            @update:file="onAvatarChange"
          />

          <div class="row full-width q-mt-md q-col-gutter-sm">
            <DefaultInput
              :model-value="form.name"
              :error="!!validationErrors.name"
              :error-message="validationErrors.name"
              class="col-12"
              disable
              label="Nome da Unidade"
              outlined
            />

            <DefaultInput
              :model-value="form.social_reason"
              :error="!!validationErrors.social_reason"
              :error-message="validationErrors.social_reason"
              class="col-12"
              disable
              label="Razão Social"
              outlined
            />

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

            <DefaultInput
              :model-value="form.cnpj"
              :error="!!validationErrors.cnpj"
              :error-message="validationErrors.cnpj"
              :mask="masks.Brasil.cnpj"
              :rules="[inputRules.cnpj]"
              class="col-4"
              disable
              label="CNPJ"
              outlined
            />

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

            <DefaultInput
              :model-value="form.name_responsible"
              :error="!!validationErrors.name_responsible"
              :error-message="validationErrors.name_responsible"
              class="col-4"
              disable
              label="Franqueado Operador"
              outlined
            />

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

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

            <DefaultInput
              :model-value="form.address_number"
              :error="!!validationErrors.address_number"
              :error-message="validationErrors.address_number"
              :rules="[inputRules.required]"
              class="col-3"
              disable
              label="Número"
              outlined
            />

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

            <DefaultInput
              :model-value="stateName"
              :error="!!validationErrors.state_id"
              :error-message="validationErrors.state_id"
              class="col-4"
              disable
              label="Estado"
              outlined
            />

            <DefaultInput
              :model-value="cityName"
              :error="!!validationErrors.city_id"
              :error-message="validationErrors.city_id"
              class="col-4"
              disable
              label="Cidade"
              outlined
            />

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

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

            <DefaultInput
              :model-value="form.secondary_email"
              :error="!!validationErrors.secondary_email"
              :error-message="validationErrors.secondary_email"
              class="col-6"
              disable
              label="E-mail Administrativo"
              outlined
            />

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

            <DefaultInput
              :model-value="form.cell_number"
              :error="!!validationErrors.cell_number"
              :error-message="validationErrors.cell_number"
              :rules="[inputRules.required]"
              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="form.password"
              class="col-6"
              label="Nova Senha"
              outlined
              :error="!!validationErrors.password"
              :error-message="validationErrors.password"
              :rules="
                form.password
                  ? [inputRules.password]
                  : []
              "
            />

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

      <div class="row justify-end q-mt-md items-end full-width q-px-xs">
        <q-btn
          v-if="canEdit"
          color="primary"
          label="Salvar"
          no-caps
          type="submit"
          :disable="!hasChanges"
          :loading="loading"
        />
      </div>
    </DefaultForm>
  </div>
</template>

<script setup>
import {
  computed,
  onMounted,
  ref,
  useTemplateRef,
} from "vue";

import { getUnitMe, updateUnitMe } from "src/api/unit";
import { permissionStore } from "src/stores/permission";
import { updateUserMe } from "src/api/user.js";
import { useForm } from "src/composables/useForm";
import { useInputRules } from "src/composables/useInputRules";
import { useScroll } from "src/composables/useScroll";
import { useSubmitHandler } from "src/composables/useSubmitHandler";

import masks from "src/helpers/masks";

import AvatarImageComponent from "src/components/shared/AvatarImageComponent.vue";

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

defineProps({
  unitId: {
    type: Number,
    default: null,
  },
});

const { inputRules } = useInputRules();
const { scrollToComponent } = useScroll();

const permissions = permissionStore();

const avatarRef = useTemplateRef("avatarRef");
const formRef = useTemplateRef("formRef");
const scrollAreaRef = useTemplateRef("scrollAreaRef");

const cityName = ref("");
const newAvatarFile = ref(null);
const stateName = ref("");

const canEdit = computed(() =>
  permissions.getAccess("franchisee_unit", "edit"),
);

const {
  form,
  getUpdatedFields,
  hasUpdatedFields,
  setUpdateFormAsOriginal,
} = useForm({
  address_number: null,
  cell_number: null,
  city_id: null,
  cnpj: null,
  complement: null,
  email: null,
  fantasy_name: "",
  name: null,
  name_responsible: null,
  neighborhood: null,
  password: null,
  password_confirmation: null,
  phone_number: null,
  postal_code: null,
  secondary_email: null,
  social_reason: null,
  state_id: null,
  state_registration: null,
  street: null,
});

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

const {
  loading,
  validationErrors,
  execute,
} = useSubmitHandler({
  containerRef: scrollAreaRef,
  formRef,
  onSuccess: () => {
    setUpdateFormAsOriginal();
  },
  scrollFn: scrollToComponent,
});

const onAvatarChange = (file) => {
  newAvatarFile.value = file;
};

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

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

      await updateUnitMe(formData);

      newAvatarFile.value = null;
    }

    const changedFields = {
      ...getUpdatedFields.value,
    };

    delete changedFields.password;
    delete changedFields.password_confirmation;

    if (Object.keys(changedFields).length) {
      await updateUnitMe(changedFields);
    }

    if (form.password) {
      await updateUserMe({
        password: form.password,
      });

      form.password = null;
      form.password_confirmation = null;
    }
  });
};

onMounted(async () => {
  try {
    const unit = await getUnitMe();

    const fantasyName = String(
      unit.fantasy_name ?? "",
    ).trim();

    form.address_number = unit.address_number;
    form.cell_number = unit.cell_number;
    form.cnpj = unit.cnpj;
    form.complement = unit.complement;
    form.email = unit.email;

    form.fantasy_name = [
      "null",
      "undefined",
    ].includes(fantasyName.toLowerCase())
      ? ""
      : fantasyName;

    form.name = unit.name ?? null;
    form.name_responsible = unit.name_responsible;
    form.neighborhood = unit.neighborhood;
    form.phone_number = unit.phone_number;
    form.postal_code = unit.postal_code;
    form.secondary_email = unit.secondary_email;
    form.social_reason = unit.social_reason;

    form.state_registration =
      unit.state_registration;

    form.street = unit.street;

    cityName.value = unit.city?.name ?? "";
    stateName.value = unit.state?.name ?? "";

    if (unit.avatar_url) {
      avatarRef.value?.setImageUrl(
        unit.avatar_url,
      );
    }

    setUpdateFormAsOriginal();
  } catch (error) {
    console.error(error);
  }
});
</script>

<style scoped>
.unit-data-scroll-area {
  height: calc(100vh - 310px);
  min-height: 420px;
}
</style>
