<template>
  <div class="q-pa-md">
    <DefaultForm 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
            v-model="form.name"
            v-model:error="validationErrors.name"
            :error-message="validationErrors.name"
            label="Nome da Unidade"
            class="col-12"
            outlined
            :rules="[inputRules.required]"
          />

          <DefaultInput
            v-model="form.social_reason"
            v-model:error="validationErrors.social_reason"
            :error-message="validationErrors.social_reason"
            label="Razão Social"
            class="col-12"
            outlined
            :rules="[inputRules.required]"
          />

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

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

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

          <DefaultInput
            v-model="form.name_responsible"
            v-model:error="validationErrors.name_responsible"
            :error-message="validationErrors.name_responsible"
            label="Responsável"
            class="col-4"
            outlined
            :rules="[inputRules.required]"
          />

          <DefaultCepInput
            v-model="form.postal_code"
            v-model:error="validationErrors.postal_code"
            :error-message="validationErrors.postal_code"
            class="col-3"
            outlined
            :rules="[inputRules.required]"
            @rua="form.street = $event"
            @bairro="form.neighborhood = $event"
            @uf="stateSelectRef?.selectStateByCode($event)"
            @cidade="citySelectRef?.selectCityByName($event)"
          />

          <DefaultInput
            v-model="form.street"
            v-model:error="validationErrors.street"
            :error-message="validationErrors.street"
            label="Endereço"
            class="col-6"
            outlined
            :rules="[inputRules.required]"
          />

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

          <DefaultInput
            v-model="form.neighborhood"
            v-model:error="validationErrors.neighborhood"
            :error-message="validationErrors.neighborhood"
            label="Bairro"
            class="col-4"
            outlined
            :rules="[inputRules.required]"
          />

          <StateSelect
            ref="stateSelectRef"
            v-model="selectedState"
            v-model:error="validationErrors.state_id"
            :error-message="validationErrors.state_id"
            label="Estado"
            class="col-4"
            outlined
            :rules="[inputRules.required]"
          />

          <CitySelect
            ref="citySelectRef"
            v-model="selectedCity"
            v-model:error="validationErrors.city_id"
            :error-message="validationErrors.city_id"
            label="Cidade"
            class="col-4"
            outlined
            :state="selectedState"
            :rules="[inputRules.required]"
          />

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

          <DefaultInput
            v-model="form.email"
            v-model:error="validationErrors.email"
            :error-message="validationErrors.email"
            label="E-mail Principal"
            class="col-6"
            outlined
            :rules="[inputRules.required, inputRules.email]"
          />

          <DefaultInput
            v-model="form.secondary_email"
            v-model:error="validationErrors.secondary_email"
            :error-message="validationErrors.secondary_email"
            label="E-mail Administrativo"
            class="col-6"
            outlined
            :rules="[inputRules.email]"
          />

          <DefaultInput
            v-model="form.phone_number"
            v-model:error="validationErrors.phone_number"
            :error-message="validationErrors.phone_number"
            label="Telefone"
            class="col-6"
            outlined
            :mask="masks.Brasil.telefone"
          />

          <DefaultInput
            v-model="form.cell_number"
            v-model:error="validationErrors.cell_number"
            :error-message="validationErrors.cell_number"
            label="Celular"
            class="col-6"
            outlined
            :mask="masks.Brasil.celular"
            :rules="[inputRules.required]"
          />
        </div>

        <div class="row justify-end q-mt-md items-end full-width q-px-xs">
          <div class="row q-gutter-sm">
            <q-btn label="Cancelar" color="primary" outline @click="onCancel" />
            <q-btn
              label="Salvar"
              color="primary-2"
              :loading="loading"
              @click="onSave"
            />
          </div>
        </div>
      </div>
    </DefaultForm>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import { useRouter } from "vue-router";
import DefaultInput from "src/components/defaults/DefaultInput.vue";
import DefaultCepInput from "src/components/defaults/DefaultCepInput.vue";
import AvatarImageComponent from "src/components/shared/AvatarImageComponent.vue";
import StateSelect from "src/components/selects/StateSelect.vue";
import CitySelect from "src/components/selects/CitySelect.vue";
import { useSubmitHandler } from "src/composables/useSubmitHandler";
import { useInputRules } from "src/composables/useInputRules";
import { createUnit, getUnit, updateUnit } from "src/api/unit";
import masks from "src/helpers/masks";

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

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

const router = useRouter();
const formRef = ref(null);
const avatarRef = ref(null);
const stateSelectRef = ref(null);
const citySelectRef = ref(null);

const selectedState = ref(null);
const selectedCity = ref(null);

const { inputRules } = useInputRules();

watch(selectedState, (state) => {
  form.value.state_id = state?.value ?? null;
});

watch(selectedCity, (city) => {
  form.value.city_id = city?.value ?? null;
});

function onAvatarChange(file) {
  form.value.avatar = file;
}

onMounted(async () => {
  if (!props.unitId) return;

  try {
    const unit = await getUnit(props.unitId);

    form.value.name = unit.name;
    const fantasyName = String(unit.fantasy_name ?? "").trim();
    form.value.fantasy_name = ["null", "undefined"].includes(
      fantasyName.toLowerCase(),
    )
      ? ""
      : fantasyName;
    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;
    form.value.state_id = unit.state_id;
    form.value.city_id = unit.city_id;

    if (unit.state_id) {
      stateSelectRef.value?.selectStateById(unit.state_id);
    }
    if (unit.city_id) {
      citySelectRef.value?.selectCityById(unit.city_id);
    }
    if (unit.avatar_url) {
      avatarRef.value?.setImageUrl(unit.avatar_url);
    }

    props.setUpdateFormAsOriginal();
  } catch (e) {
    console.error(e);
  }
});

const { loading, validationErrors, execute } = useSubmitHandler({
  formRef,
  onSuccess: (result) => {
    if (props.unitId) {
      router.push({ name: "FranchiseePage" });
    } else {
      router.push({ name: "UnitEditPage", params: { id: result.id } });
    }
  },
});

async function onSave() {
  await execute(() => {
    const formData = props.getFormAsFormData();
    if (props.unitId) {
      return updateUnit(props.unitId, formData);
    }
    return createUnit(formData);
  });
}

function onCancel() {
  router.push({ name: "FranchiseePage" });
}
</script>
