<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
            v-model="form.name"
            label="Nome da Unidade"
            class="col-12"
            outlined
            :rules="[inputRules.required]"
          />

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

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

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

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

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

          <DefaultCepInput
            v-model="form.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"
            label="Endereço"
            class="col-6"
            outlined
            :rules="[inputRules.required]"
          />

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

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

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

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

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

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

          <DefaultInput
            v-model="form.secondary_email"
            label="E-mail Secundário"
            class="col-6"
            outlined
            :rules="[inputRules.email]"
          />

          <DefaultInput
            v-model="form.phone_number"
            label="Telefone"
            class="col-6"
            outlined
            :mask="masks.Brasil.telefone"
            :rules="[inputRules.required]"
          />

          <DefaultInput
            v-model="form.cell_number"
            label="Celular"
            class="col-6"
            outlined
            :mask="masks.Brasil.celular"
          />
        </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>
    </q-form>
  </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, 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>
