<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card
      class="q-dialog-plugin overflow-hidden"
      style="width: 860px; max-width: 95vw"
    >
      <DefaultDialogHeader :title="dialogTitle" @close="onDialogCancel" />

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

          <div class="row q-col-gutter-sm">
            <DefaultInput
              v-model="form.name"
              v-model:error="validationErrors.name"
              class="col-8"
              label="Nome completo"
              outlined
              :rules="[inputRules.required]"
            />

            <DefaultInput
              v-model="form.role"
              v-model:error="validationErrors.role"
              class="col-4"
              label="Função"
              outlined
            />

            <DefaultInput
              v-model="form.social_name"
              v-model:error="validationErrors.social_name"
              class="col-6"
              label="Nome social"
              outlined
            />

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

            <DefaultInput
              v-model="form.rg"
              v-model:error="validationErrors.rg"
              class="col-3"
              label="RG"
              outlined
            />

            <DefaultInput
              v-model="birthDateDisplay"
              v-model:error="validationErrors.birth_date"
              class="col-3"
              label="Data de Nascimento"
              placeholder="DD/MM/AAAA"
              outlined
              :mask="masks.Brasil.date"
            />

            <DefaultInput
              v-model="form.participation"
              v-model:error="validationErrors.participation"
              class="col-3"
              label="Participação (%)"
              max="100"
              min="0"
              outlined
              type="number"
            />

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

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

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

            <DefaultInput
              v-model="form.cell_number"
              v-model:error="validationErrors.cell_number"
              class="col-6"
              label="Celular"
              outlined
              :mask="masks.Brasil.celular"
            />

            <DefaultCepInput
              v-model="form.postal_code"
              v-model:error="validationErrors.postal_code"
              class="col-6"
              outlined
              @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"
              class="col-6"
              label="Endereço"
              outlined
            />

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

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

            <StateSelect
              ref="stateSelectRef"
              v-model="selectedState"
              v-model:error="validationErrors.state_id"
              class="col-4"
              label="Estado"
              outlined
            />

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

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

        <q-card-actions>
          <q-space />

          <q-btn
            color="negative"
            label="Cancelar"
            outline
            @click="onDialogCancel"
          />

          <q-btn
            color="primary-2"
            type="submit"
            :label="partner ? 'Salvar' : 'Adicionar'"
            :loading="loading"
          />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { createPartner, updatePartner } from "src/api/unit_partner";
import { formatDateDMYtoYMD, formatDateYMDtoDMY } from "src/helpers/utils";
import { onMounted, ref, watch } from "vue";
import { useDialogPluginComponent } from "quasar";
import { useFormUpdateTracker } from "src/composables/useFormUpdateTracker";
import { useInputRules } from "src/composables/useInputRules";
import { useSubmitHandler } from "src/composables/useSubmitHandler";
import masks from "src/helpers/masks";

import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
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";

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

const { offlineMode, partner, unitId } = defineProps({
  offlineMode: {
    type: Boolean,
    default: false,
  },
  partner: {
    type: Object,
    default: null,
  },
  unitId: {
    type: Number,
    default: null,
  },
});

const { inputRules } = useInputRules();

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

const dialogTitle = partner ? "Editar Sócio" : "Adicionar Sócio";

const { form, getFormAsFormData } = useFormUpdateTracker({
  address_number: partner?.address_number ?? null,
  birth_date: partner?.birth_date ?? null,
  cell_number: partner?.cell_number ?? null,
  city_id: partner?.city_id ?? null,
  complement: partner?.complement ?? null,
  cpf: partner?.cpf ?? null,
  email: partner?.email ?? null,
  name: partner?.name ?? null,
  neighborhood: partner?.neighborhood ?? null,
  participation: partner?.participation ?? null,
  phone_number: partner?.phone_number ?? null,
  postal_code: partner?.postal_code ?? null,
  rg: partner?.rg ?? null,
  role: partner?.role ?? null,
  secondary_email: partner?.secondary_email ?? null,
  social_name: partner?.social_name ?? null,
  state_id: partner?.state_id ?? null,
  street: partner?.street ?? null,
  unit_id: unitId,
});

const avatarRef = ref(null);
const avatarChanged = ref(false);
const avatarFile = ref(null);
const birthDateDisplay = ref(
  partner?.birth_date ? formatDateYMDtoDMY(partner.birth_date) : null,
);
const stateSelectRef = ref(null);
const citySelectRef = ref(null);
const formRef = ref(null);
const selectedState = ref(null);
const selectedCity = ref(null);

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

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

async function onOKClick() {
  if (offlineMode) {
    const partnerData = { ...form };

    if (avatarFile.value instanceof File) {
      if (partner?.avatar_url?.startsWith("blob:")) {
        URL.revokeObjectURL(partner.avatar_url);
      }

      partnerData.avatar = avatarFile.value;

      partnerData.avatar_url = URL.createObjectURL(avatarFile.value);
    } else if (partner?.avatar_url) {
      partnerData.avatar_url = partner.avatar_url;
    }

    onDialogOK(partnerData);

    return;
  }

  await execute(() => {
    const formData = getFormAsFormData();

    if (avatarChanged.value) {
      formData.append("avatar", avatarFile.value ?? "");
    }

    if (partner) {
      return updatePartner(partner.id, formData);
    }

    return createPartner(formData);
  });
}

watch(birthDateDisplay, (val) => {
  try {
    form.birth_date = val?.length === 10 ? formatDateDMYtoYMD(val) : null;
  } catch {
    form.birth_date = null;
  }
});

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

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

onMounted(() => {
  if (!partner) return;

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

  if (partner.state_id) {
    stateSelectRef.value?.selectStateById(partner.state_id);
  }

  if (partner.city_id) {
    citySelectRef.value?.selectCityById(partner.city_id);
  }
});
</script>
