<template>
  <DefaultForm ref="formRef" @submit="onSave">
    <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"
        :error="!!validationErrors.name"
        :error-message="validationErrors.name"
        label="Nome do Aluno"
        class="col-6"
        :rules="[inputRules.required]"
      />

      <DefaultInputDatePicker
        v-model="form.birthdate"
        :error="!!validationErrors.birth_date"
        :error-message="validationErrors.birth_date"
        label="Data de Nascimento"
        class="col-6"
      />

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

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

      <DefaultInput
        v-model="form.email"
        :error="!!validationErrors.email"
        :error-message="validationErrors.email"
        label="E-mail"
        class="col-6"
        type="email"
      />

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

      <DefaultCepInput
        v-model="form.cep"
        :error="!!validationErrors.postal_code"
        :error-message="validationErrors.postal_code"
        class="col-4"
        @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"
        :error="!!validationErrors.street"
        :error-message="validationErrors.street"
        label="Endereço"
        class="col-5"
      />

      <DefaultInput
        v-model="form.address_number"
        :error="!!validationErrors.address_number"
        :error-message="validationErrors.address_number"
        label="Número"
        class="col-3"
      />

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

      <CitySelect
        ref="citySelectRef"
        v-model="selectedCity"
        :error="!!validationErrors.city_id"
        :error-message="validationErrors.city_id"
        label="Cidade"
        class="col-4"
        :state="selectedState"
        :initial-id="props.student.city_id"
      />

      <StateSelect
        ref="stateSelectRef"
        v-model="selectedState"
        :error="!!validationErrors.state_id"
        :error-message="validationErrors.state_id"
        label="Estado"
        class="col-4"
        :initial-id="props.student.state_id"
      />

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

      <DefaultInput
        v-model="form.payer"
        :error="!!validationErrors.payer_name"
        :error-message="validationErrors.payer_name"
        label="Pagador"
        class="col-6"
      />

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

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

  </DefaultForm>
</template>

<script setup>
import { ref, watch, onMounted, useTemplateRef } from "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 masks from "src/helpers/masks";
import { formatDateYMDtoDMY, formatDateDMYtoYMD } from "src/helpers/utils";

const props = defineProps({
  student: {
    type: Object,
    required: true,
  },
  validationErrors: {
    type: Object,
    default: () => ({}),
  },
});

const { inputRules } = useInputRules();

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

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

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

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

const form = ref({
  name: props.student.name ?? null,
  birthdate: props.student.birth_date
    ? formatDateYMDtoDMY(props.student.birth_date)
    : null,
  cpf: props.student.document_number ?? null,
  gender: props.student.gender ?? "no_preference",
  email: props.student.email ?? null,
  phone: props.student.phone ?? null,
  cep: props.student.postal_code ?? null,
  address: props.student.street ?? null,
  address_number: props.student.address_number ?? null,
  neighborhood: props.student.neighborhood ?? null,
  state_id: props.student.state_id ?? null,
  city_id: props.student.city_id ?? null,
  complement: props.student.complement ?? null,
  payer: props.student.payer_name ?? null,
  how_found: props.student.how_did_you_know_us ?? null,
  notes: props.student.notes ?? null,
});

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

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

onMounted(() => {
  if (props.student.photo_url) {
    avatarRef.value?.setImageUrl(props.student.photo_url);
  }
});

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,
  };
}

defineExpose({
  validate: () => formRef.value?.validate(),
  buildPayload,
});
</script>
