<template>
  <q-form ref="formDadosRef" @submit="saveDados">
    <div class="q-pr-md q-pb-md bg-violet-light">
      <DefaultFilePicker
        v-model="logoFile"
        type="image"
        :label="$t('parceiro.logo')"
        :initial-image="initialLogoUrl"
        style="height: 220px; max-width: 280px"
      />
    </div>

    <q-card flat class="cadastro-card q-pa-md">
      <div v-if="loading" class="flex flex-center q-pa-xl">
        <q-spinner color="violet-normal" size="40px" />
      </div>

      <div v-else class="row q-col-gutter-sm">
        <DefaultInput
          v-model="formDados.company_name"
          v-model:error="errorsDados.company_name"
          :rules="[inputRules.required]"
          :label="$t('parceiro.company_name')"
          class="col-12"
        />
        <DefaultInput
          v-model="formDados.cnpj"
          v-model:error="errorsDados.cnpj"
          :label="$t('common.terms.cnpj')"
          :placeholder="'00.000.000/0000-00'"
          :mask="'##.###.###/####-##'"
          class="col-12"
        />
        <PartnerAgreementCategorySelect
          v-model="selectedCategory"
          v-model:error="errorsDados.category_id"
          class="col-12"
        />
        <DefaultInput
          v-model="formDados.responsible"
          v-model:error="errorsDados.responsible"
          :label="$t('parceiro.responsible')"
          class="col-12"
        />
        <DefaultInput
          v-model="formDados.discount_percentage"
          v-model:error="errorsDados.discount_percentage"
          :label="$t('parceiro.discount_percentage')"
          type="number"
          suffix="%"
          class="col-12"
        />
        <DefaultInput
          v-model="formDados.description"
          v-model:error="errorsDados.description"
          :label="$t('common.terms.description')"
          type="textarea"
          autogrow
          class="col-12"
        />
      </div>
    </q-card>

    <div class="row justify-end q-py-md bg-violet-light">
      <q-btn
        unelevated
        class="btn-gradient"
        :label="$t('common.actions.save')"
        icon="mdi-check"
        type="submit"
        :loading="loadingDados"
        :disable="!hasUpdatedDados && !logoFile"
      />
    </div>
  </q-form>
</template>

<script setup>
import { ref, watch, useTemplateRef } from "vue";
import { useRouter } from "vue-router";
import { useQuasar } from "quasar";
import { useI18n } from "vue-i18n";
import { useInputRules } from "src/composables/useInputRules";
import { useFormUpdateTracker } from "src/composables/useFormUpdateTracker";
import { useSubmitHandler } from "src/composables/useSubmitHandler";
import {
  getPartnerAgreementDados,
  createPartnerAgreement,
  updatePartnerAgreement,
  uploadPartnerLogo,
} from "src/api/partnerAgreement";

import DefaultInput from "src/components/defaults/DefaultInput.vue";
import DefaultFilePicker from "src/components/defaults/DefaultFilePicker.vue";
import PartnerAgreementCategorySelect from "src/components/selects/PartnerAgreementCategorySelect.vue";

const props = defineProps({
  partnerId: { type: Number, default: null },
  active:    { type: Boolean, default: false },
});

const emit = defineEmits(["partner-created", "partner-saved"]);

const router = useRouter();
const $q = useQuasar();
const { t } = useI18n();
const { inputRules } = useInputRules();

const formDadosRef = useTemplateRef("formDadosRef");
const logoFile = ref(null);
const initialLogoUrl = ref(null);
const selectedCategory = ref(null);
const loading = ref(false);
const loaded = ref(false);

const {
  form: formDados,
  getUpdatedFields: updatedDados,
  hasUpdatedFields: hasUpdatedDados,
  setUpdateFormAsOriginal,
} = useFormUpdateTracker({
  company_name:        "",
  cnpj:                "",
  category_id:         null,
  responsible:         "",
  discount_percentage: null,
  description:         "",
});

const {
  loading: loadingDados,
  validationErrors: errorsDados,
  execute: execDados,
} = useSubmitHandler({ formRef: formDadosRef });

watch(selectedCategory, (val) => {
  formDados.category_id = val?.value ?? null;
});

const populate = (p) => {
  formDados.company_name        = p.company_name        ?? "";
  formDados.cnpj                = p.cnpj                ?? "";
  formDados.category_id         = p.category_id         ?? null;
  formDados.responsible         = p.responsible         ?? "";
  formDados.discount_percentage = p.discount_percentage != null ? String(p.discount_percentage) : null;
  formDados.description         = p.description         ?? "";

  selectedCategory.value = p.category
    ? { label: p.category.name, value: p.category.id }
    : null;

  initialLogoUrl.value = p.logo?.url ?? null;
  setUpdateFormAsOriginal();
};

const loadData = async () => {
  if (!props.partnerId) { loaded.value = true; return; }
  loading.value = true;
  try {
    const p = await getPartnerAgreementDados(props.partnerId);
    populate(p);
    loaded.value = true;
  } catch {
    $q.notify({ type: "negative", message: t("http.errors.failed") });
  } finally {
    loading.value = false;
  }
};

const saveDados = async () => {
  await execDados(async () => {
    let savedPartner;
    if (props.partnerId) {
      savedPartner = await updatePartnerAgreement(props.partnerId, updatedDados.value);
    } else {
      savedPartner = await createPartnerAgreement({ ...formDados });
      emit("partner-created", savedPartner);
      await router.replace({ name: "ParceiroCadastroPage", params: { id: savedPartner.id } });
    }
    if (logoFile.value instanceof File) {
      const uploadedMedia = await uploadPartnerLogo(savedPartner.id ?? props.partnerId, logoFile.value);
      savedPartner = { ...savedPartner, logo: uploadedMedia };
      initialLogoUrl.value = uploadedMedia.url ?? null;
      logoFile.value = null;
    }
    populate(savedPartner);
    emit("partner-saved", savedPartner);
    $q.notify({ type: "positive", message: t("http.success") });
  });
};

watch(() => props.active, (isActive) => {
  if (isActive && !loaded.value) loadData();
}, { immediate: true });
</script>

<style lang="scss" scoped>
@use "src/css/quasar.variables.scss";

.cadastro-card {
  border-radius: 12px;
  background: white;
}

.btn-gradient {
  background: linear-gradient(90deg, #4d1658 0%, #8b30a5 100%) !important;
  color: white !important;
  border-radius: 8px !important;
  padding: 8px 16px;
}

.btn-gradient :deep(.q-icon) {
  color: white !important;
}
</style>
