<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card
      class="q-dialog-plugin overflow-hidden"
      style="width: 100%; max-width: 1100px"
    >
      <DefaultDialogHeader title="Cadastrar Aluno" @close="onDialogCancel" />

      <q-form ref="formRef" @submit="onOKClick">
        <q-card-section class="q-pt-none">
          <div class="flex justify-center q-mb-md">
            <AvatarImageComponent
              ref="avatarRef"
              @update:file="onAvatarChange"
            />
          </div>

          <div class="row q-col-gutter-sm">
            <DefaultInput
              v-model="form.name"
              label="Nome do Aluno"
              class="col-6"
              :rules="[inputRules.required]"
            />

            <DefaultInputDatePicker
              v-model="form.birthdate"
              label="Data de Nascimento"
              class="col-6"
            />

            <DefaultInput
              v-model="form.cpf"
              label="CPF"
              class="col-6"
              :mask="masks.Brasil.cpf"
              :rules="[inputRules.cpf]"
            />

            <DefaultSelect
              v-model="form.gender"
              label="Gênero"
              class="col-6"
              emit-value
              map-options
              :options="genderOptions"
            />

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

            <DefaultInput
              v-model="form.phone"
              label="Celular com DDD"
              class="col-6"
              :mask="masks.Brasil.celular"
            />

            <DefaultCepInput
              v-model="form.cep"
              class="col-4"
              :rules="[inputRules.cep]"
              @rua="(v) => (form.address = v)"
              @bairro="(v) => (form.neighborhood = v)"
              @uf="(v) => stateSelectRef?.selectStateByCode(v)"
              @cidade="(v) => citySelectRef?.selectCityByName(v)"
            />

            <DefaultInput
              v-model="form.address"
              label="Endereço"
              class="col-5"
            />

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

            <DefaultInput
              v-model="form.neighborhood"
              label="Bairro"
              class="col-4"
            />

            <CitySelect
              ref="citySelectRef"
              v-model="selectedCity"
              label="Cidade"
              class="col-4"
              :state="selectedState"
            />

            <StateSelect
              ref="stateSelectRef"
              v-model="selectedState"
              label="Estado"
              class="col-4"
            />

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

            <DefaultInput v-model="form.payer" label="Pagador" class="col-6" />

            <DefaultSelect
              v-model="form.how_found"
              label="Como nos conheceu?"
              class="col-12"
              emit-value
              map-options
              :options="howFoundOptions"
            />

            <DefaultInput
              v-model="form.notes"
              label="Observações"
              class="col-12"
              type="textarea"
              :input-style="{ minHeight: '120px' }"
              autogrow
            />
          </div>
        </q-card-section>

        <q-card-actions align="right">
          <q-btn
            outline
            color="primary"
            label="CANCELAR"
            @click="onDialogCancel"
          />
          <q-btn
            color="primary"
            label="CADASTRAR"
            type="submit"
            :loading="loading"
          />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { ref, watch, useTemplateRef } from "vue";
import { useDialogPluginComponent } from "quasar";

import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
import DefaultInput from "src/components/defaults/DefaultInput.vue";
import DefaultSelect from "src/components/defaults/DefaultSelect.vue";
import DefaultInputDatePicker from "src/components/defaults/DefaultInputDatePicker.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 { useInputRules } from "src/composables/useInputRules";
import { useSubmitHandler } from "src/composables/useSubmitHandler";
import { createStudent } from "src/api/student";
import masks from "src/helpers/masks";
import { formatDateDMYtoYMD } from "src/helpers/utils";

defineEmits([...useDialogPluginComponent.emits]);

const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } =
  useDialogPluginComponent();

const { inputRules } = useInputRules();

const formRef = useTemplateRef("formRef");
const stateSelectRef = useTemplateRef("stateSelectRef");
const citySelectRef = useTemplateRef("citySelectRef");

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

const form = ref({
  name: null,
  birthdate: null,
  cpf: null,
  gender: "no_preference",
  email: null,
  phone: null,
  cep: null,
  address: null,
  address_number: null,
  neighborhood: null,
  state_id: null,
  city_id: null,
  complement: null,
  payer: null,
  how_found: null,
  notes: null,
});

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

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

const genderOptions = ref([
  { label: "Prefiro não informar", value: "no_preference" },
  { label: "Masculino", value: "male" },
  { label: "Feminino", value: "female" },
  { label: "Outro", value: "other" },
]);

const howFoundOptions = ref([
  { label: "Indicação", value: "referral" },
  { label: "Redes Sociais", value: "social_media" },
  { label: "Google", value: "google" },
  { label: "Outro", value: "other" },
]);

const { loading, execute } = useSubmitHandler({
  formRef,
  onSuccess: () => {
    onDialogOK(true);
  },
});

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

function buildPayload() {
  if (avatarFile.value) {
    const formData = new FormData();
    formData.append("name", form.value.name ?? "");
    if (form.value.birthdate) {
      formData.append("birth_date", formatDateDMYtoYMD(form.value.birthdate));
    }
    formData.append("document_number", form.value.cpf ?? "");
    formData.append("gender", form.value.gender ?? "");
    formData.append("email", form.value.email ?? "");
    formData.append("phone", form.value.phone ?? "");
    formData.append("postal_code", form.value.cep ?? "");
    formData.append("street", form.value.address ?? "");
    formData.append("address_number", form.value.address_number ?? "");
    formData.append("neighborhood", form.value.neighborhood ?? "");
    if (form.value.state_id) {
      formData.append("state_id", form.value.state_id);
    }
    if (form.value.city_id) {
      formData.append("city_id", form.value.city_id);
    }
    formData.append("complement", form.value.complement ?? "");
    formData.append("payer_name", form.value.payer ?? "");
    formData.append("how_did_you_know_us", form.value.how_found ?? "");
    formData.append("notes", form.value.notes ?? "");
    formData.append("avatar", avatarFile.value);
    return formData;
  }

  return {
    name: form.value.name,
    birth_date: form.value.birthdate
      ? formatDateDMYtoYMD(form.value.birthdate)
      : null,
    document_number: form.value.cpf,
    gender: form.value.gender,
    email: form.value.email || null,
    phone: form.value.phone,
    postal_code: form.value.cep,
    street: form.value.address,
    address_number: form.value.address_number,
    neighborhood: form.value.neighborhood,
    state_id: form.value.state_id,
    city_id: form.value.city_id,
    complement: form.value.complement,
    payer_name: form.value.payer,
    how_did_you_know_us: form.value.how_found,
    notes: form.value.notes,
  };
}

async function onOKClick() {
  await execute(() => createStudent(buildPayload()));
}
</script>
