<template>
  <q-form ref="formHorarioRef" @submit="saveHorario">
    <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>

      <template v-else>
        <div class="row q-col-gutter-sm">
          <DefaultInput
            v-model="formHorario.working_hours"
            v-model:error="errorsHorario.working_hours"
            :label="$t('parceiro.working_hours')"
            :placeholder="$t('parceiro.working_hours_placeholder')"
            class="col-12"
          />
          <DefaultInputDatePicker
            v-model:untreated-date="formHorario.contract_start"
            v-model:error="errorsHorario.contract_start"
            :label="$t('parceiro.contract_start')"
            class="col-md-6 col-12"
          />
          <DefaultInputDatePicker
            v-model:untreated-date="formHorario.contract_end"
            v-model:error="errorsHorario.contract_end"
            :label="$t('parceiro.contract_end')"
            class="col-md-6 col-12"
          />
        </div>

        <div v-if="contractMedia.length > 0" class="q-mt-md">
          <div class="text-subtitle2 text-violet-normal q-mb-xs">{{ $t("parceiro.contract_files") }}</div>
          <div class="row q-col-gutter-xs">
            <div v-for="media in contractMedia" :key="media.id" class="col-auto">
              <q-chip
                removable
                clickable
                color="violet-light"
                text-color="violet-normal"
                icon="mdi-file-outline"
                :label="media.name"
                @click="openMedia(media)"
                @remove="removeMedia(media)"
              />
            </div>
          </div>
        </div>
      </template>
    </q-card>

    <div class="row justify-end items-center q-pt-md bg-violet-light" style="gap: 8px">
      <q-file
        ref="mediaFileInputRef"
        v-model="newMediaFile"
        accept=".pdf,.doc,.docx,.png,.jpg,.jpeg"
        style="display: none"
        @update:model-value="onMediaFileSelected"
      />
      <q-btn
        unelevated
        class="btn-gradient"
        :label="$t('parceiro.add_file')"
        icon="mdi-paperclip"
        @click="triggerMediaUpload"
      />
      <q-btn
        unelevated
        class="btn-gradient"
        :label="$t('common.actions.save')"
        icon="mdi-check"
        type="submit"
        :loading="loadingHorario"
        :disable="!hasUpdatedHorario"
      />
    </div>
  </q-form>
</template>

<script setup>
import { ref, watch, useTemplateRef } from "vue";
import { useQuasar } from "quasar";
import { useI18n } from "vue-i18n";
import { useFormUpdateTracker } from "src/composables/useFormUpdateTracker";
import { useSubmitHandler } from "src/composables/useSubmitHandler";
import {
  getPartnerAgreementContrato,
  updatePartnerAgreement,
  uploadPartnerMedia,
  deletePartnerMedia,
} from "src/api/partnerAgreement";

import DefaultInput from "src/components/defaults/DefaultInput.vue";
import DefaultInputDatePicker from "src/components/defaults/DefaultInputDatePicker.vue";

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

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

const $q = useQuasar();
const { t } = useI18n();

const formHorarioRef = useTemplateRef("formHorarioRef");
const mediaFileInputRef = useTemplateRef("mediaFileInputRef");
const newMediaFile = ref(null);
const contractMedia = ref([]);
const loading = ref(false);
const loaded = ref(false);

const {
  form: formHorario,
  getUpdatedFields: updatedHorario,
  hasUpdatedFields: hasUpdatedHorario,
  setUpdateFormAsOriginal,
} = useFormUpdateTracker({ working_hours: "", contract_start: null, contract_end: null });

const {
  loading: loadingHorario,
  validationErrors: errorsHorario,
  execute: execHorario,
} = useSubmitHandler({ formRef: formHorarioRef });

const populate = (p) => {
  formHorario.working_hours  = p.working_hours  ?? "";
  formHorario.contract_start = p.contract_start ?? null;
  formHorario.contract_end   = p.contract_end   ?? null;
  contractMedia.value = p.media ?? [];
  setUpdateFormAsOriginal();
};

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

const triggerMediaUpload = () => {
  mediaFileInputRef.value?.pickFiles();
};

const onMediaFileSelected = async (file) => {
  if (!file) return;
  try {
    const media = await uploadPartnerMedia(props.partnerId, file);
    contractMedia.value.push(media);
  } catch {
    $q.notify({ type: "negative", message: t("http.errors.failed") });
  } finally {
    newMediaFile.value = null;
  }
};

const removeMedia = async (media) => {
  try {
    await deletePartnerMedia(props.partnerId, media.id);
    contractMedia.value = contractMedia.value.filter((m) => m.id !== media.id);
  } catch {
    $q.notify({ type: "negative", message: t("http.errors.failed") });
  }
};

const openMedia = (media) => {
  window.open(media.url, "_blank");
};

const saveHorario = async () => {
  await execHorario(async () => {
    const saved = await updatePartnerAgreement(props.partnerId, updatedHorario.value);
    populate(saved);
    emit("partner-saved", saved);
    $q.notify({ type: "positive", message: t("http.success") });
  });
};

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

<style lang="scss" scoped>
.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>
