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

      <DefaultForm
        ref="formRef"
        @submit="onOKClick"
      >
        <q-scroll-area class="dialog-form-scroll">
          <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"
                class="col-8"
                label="Nome completo"
                outlined
                :error="!!validationErrors.name"
                :error-message="validationErrors.name"
                :rules="[inputRules.required]"
              />

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        <q-card-actions
          align="right"
          class="q-px-md q-pb-md"
        >
          <q-btn
            color="primary"
            label="Cancelar"
            no-caps
            outline
            @click="onDialogCancel"
          />

          <q-btn
            color="primary"
            no-caps
            type="submit"
            :label="partner ? 'Salvar' : 'Adicionar'"
            :loading="loading"
          />
        </q-card-actions>
      </DefaultForm>
    </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 { useForm } from "src/composables/useForm";
import { useInputRules } from "src/composables/useInputRules";
import { useSubmitHandler } from "src/composables/useSubmitHandler";

import masks from "src/helpers/masks";

import AvatarImageComponent from "src/components/shared/AvatarImageComponent.vue";

import CitySelect from "src/components/selects/CitySelect.vue";
import StateSelect from "src/components/selects/StateSelect.vue";

import DefaultCepInput from "src/components/defaults/DefaultCepInput.vue";
import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
import DefaultForm from "src/components/defaults/DefaultForm.vue";
import DefaultInput from "src/components/defaults/DefaultInput.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 { dialogRef, onDialogHide, onDialogOK, onDialogCancel } =
  useDialogPluginComponent();

const { inputRules } = useInputRules();

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

const avatarChanged = ref(false);
const avatarFile = ref(null);

const birthDateDisplay = ref(
  partner?.birth_date
    ? formatDateYMDtoDMY(partner.birth_date)
    : null,
);

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

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

const {
  form,
  getFormAsFormData,
  getUpdatedFieldsAsFormData,
} = useForm({
  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 {
  loading,
  validationErrors,
  execute,
} = useSubmitHandler({
  formRef,
  onSuccess: (result) => {
    onDialogOK(result);
  },
});

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

const onOKClick = async () => {
  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 = partner
      ? getUpdatedFieldsAsFormData()
      : getFormAsFormData();

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

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

    return createPartner(formData);
  });
};

watch(birthDateDisplay, (value) => {
  try {
    form.birth_date =
      value?.length === 10
        ? formatDateDMYtoYMD(value)
        : 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>