<template>
  <div class="convenios-page">
    <input
      ref="importConvenioInput"
      type="file"
      accept=".xlsx"
      class="hidden"
      @change="onConvenioFileSelected"
    />

    <DefaultHeaderPage>
      <template #after>
        <div v-if="isAdministrador" class="flex gap-sm q-mt-md">
          <q-btn
            unelevated
            class="btn-gradient"
            :label="$t('parceiro.import_convenios')"
            icon="mdi-upload"
            padding="8px 12px"
            :loading="importingConvenios"
            @click="onImportConveniosClick"
          />
          <q-btn
            unelevated
            class="btn-gradient"
            :label="$t('common.actions.add')"
            icon="mdi-plus"
            padding="8px 12px"
            @click="onAddItem"
          />
        </div>
      </template>
    </DefaultHeaderPage>

    <div class="q-pb-sm">
      <q-input
        v-model="searchQuery"
        outlined
        dense
        bg-color="white"
        :placeholder="$t('parceiro.search_placeholder')"
        clearable
        class="convenios-page__search-input"
      >
        <template #prepend>
          <q-icon name="mdi-magnify" />
        </template>
      </q-input>
    </div>

    <div class="row q-gutter-xs q-mb-md flex-wrap">
      <div
        :class="['cat-chip', activeCategory === 'all' ? 'cat-chip--selected' : 'cat-chip--default']"
        @click="activeCategory = 'all'"
      >
        {{ $t('common.terms.all') }}
      </div>
      <div
        v-for="cat in categories"
        :key="cat.id"
        :class="['cat-chip', activeCategory === String(cat.id) ? 'cat-chip--selected' : 'cat-chip--default']"
        @click="activeCategory = String(cat.id)"
      >
        {{ cat.name }}
      </div>
    </div>

    <div v-if="loading" class="flex flex-center q-pa-xl">
      <q-spinner color="violet-normal" size="50px" />
    </div>

    <div v-else-if="filteredItems.length === 0" class="flex flex-center q-pa-xl text-grey-6">
      {{ $t("http.errors.no_records_found") }}
    </div>

    <div v-else class="row q-col-gutter-md">
      <div
        v-for="item in filteredItems"
        :key="item.id"
        class="col-xl-2 col-lg-3 col-md-4 col-sm-6 col-12"
      >
        <PartnerAgreementCard
          :partner="item"
          :editable="isAdministrador"
          @edit="onEditItem"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, useTemplateRef } from "vue";
import { useRouter } from "vue-router";
import { useQuasar } from "quasar";
import { useI18n } from "vue-i18n";
import { permissionStore } from "src/stores/permission";
import { userStore } from "src/stores/user";
import { getPartnerAgreements, importConveniosMedicos } from "src/api/partnerAgreement";
import { getCategories } from "src/api/category";
import { normalizeString } from "src/helpers/utils";
import { useImportPoller } from "src/composables/useImportPoller";
import DefaultHeaderPage from "src/components/layout/DefaultHeaderPage.vue";
import PartnerAgreementCard from "./components/PartnerAgreementCard.vue";

const router = useRouter();
const $q    = useQuasar();
const { t } = useI18n();
const permission_store = permissionStore();
const { isAdministrador } = userStore();

const loading      = ref(true);
const allItems     = ref([]);
const categories   = ref([]);
const activeCategory = ref("all");
const searchQuery  = ref("");
const importConvenioInput = useTemplateRef("importConvenioInput");
const { polling: importingConvenios, start: startConvenioPolling } = useImportPoller();

const filteredItems = computed(() => {
  let list = allItems.value;
  if (activeCategory.value !== "all") {
    list = list.filter((p) => String(p.category_id) === activeCategory.value);
  }
  if (searchQuery.value) {
    const needle = normalizeString(searchQuery.value);
    list = list.filter((p) => {
      const fields = [p.company_name, p.cnpj, p.responsible, p.email, p.phone, p.category?.name, p.address, p.city?.name];
      return fields.some((f) => f && normalizeString(String(f)).includes(needle));
    });
  }
  return list;
});

const onAddItem = () => {
  if (!permission_store.getAccess("parceiro.convenio", "add")) {
    $q.notify({ type: "negative", message: t("validation.permissions.add") });
    return;
  }
  router.push({ name: "ConvenioCadastroPage" });
};

const onEditItem = (item) => {
  if (!permission_store.getAccess("parceiro.convenio", "edit")) {
    $q.notify({ type: "negative", message: t("validation.permissions.edit") });
    return;
  }
  router.push({ name: "ConvenioCadastroPage", params: { id: item.id } });
};

const loadItems = async () => {
  const [items, cats] = await Promise.all([
    getPartnerAgreements({ type: "agreement" }),
    getCategories("agreement"),
  ]);
  allItems.value    = items;
  categories.value  = cats;
};

const onImportConveniosClick = () => {
  if (!permission_store.getAccess("parceiro.convenio", "add")) {
    $q.notify({ type: "negative", message: t("validation.permissions.add") });
    return;
  }
  importConvenioInput.value.value = null;
  importConvenioInput.value.click();
};

const onConvenioFileSelected = async (event) => {
  const file = event.target.files?.[0];
  if (!file) return;
  try {
    const { import_id } = await importConveniosMedicos(file);
    startConvenioPolling(import_id, {
      onComplete: async (stats) => {
        $q.notify({
          type: "positive",
          message: t("parceiro.import_convenios_result", {
            partners_created:     stats.partners_created,
            services_created:     stats.services_created,
            partners_inactivated: stats.partners_inactivated,
          }),
          timeout: 7000,
        });
        await loadItems();
      },
      onError:   () => $q.notify({ type: "negative", message: t("http.errors.failed") }),
      onTimeout: () => $q.notify({ type: "warning",  message: t("parceiro.import_processing") }),
    });
  } catch {
    $q.notify({ type: "negative", message: t("http.errors.failed") });
  }
};

onMounted(async () => {
  try { await loadItems(); }
  finally { loading.value = false; }
});
</script>

<style scoped>
.gap-sm { gap: 8px; }
.convenios-page { min-height: 100vh; }
.convenios-page__search-input { max-width: 700px; width: 100%; }
.cat-chip {
  display: inline-flex; align-items: center; justify-content: center;
  height: 28px; padding: 0 12px; border-radius: 5px;
  font-size: 12px; font-weight: 500; cursor: pointer;
  user-select: none; transition: background 0.15s, color 0.15s;
}
.cat-chip--default  { background: #c9a3dc; color: #fff; }
.cat-chip--selected { background: #4d1658; color: #fff; }
.btn-gradient {
  background: linear-gradient(90deg, #4d1658 0%, #8b30a5 100%) !important;
  color: white !important; border-radius: 8px !important;
}
.btn-gradient :deep(.q-icon) { color: white !important; }
</style>
