<template>
  <div class="convenios-page">
    <DefaultHeaderPage />

    <div class="convenios-page__search q-px-md q-pt-md">
      <q-input
        v-model="search"
        :placeholder="$t('associado.search_by_segment')"
        outlined
        dense
        bg-color="white"
        clearable
        class="convenios-page__search-input"
      >
        <template #prepend>
          <q-icon name="mdi-magnify" />
        </template>
      </q-input>
    </div>

    <div class="convenios-page__chips q-px-md q-pt-sm q-pb-md">
      <q-chip
        clickable
        :outline="selectedCategory !== null"
        color="violet-normal"
        text-color="white"
        class="convenios-page__chip"
        @click="selectedCategory = null"
      >
        {{ $t('common.terms.all') }}
      </q-chip>
      <q-chip
        v-for="cat in categories"
        :key="cat.value"
        clickable
        :outline="selectedCategory !== cat.value"
        color="violet-normal"
        text-color="white"
        class="convenios-page__chip"
        @click="selectedCategory = cat.value"
      >
        {{ cat.label }}
      </q-chip>
    </div>

    <div class="convenios-page__content q-px-md q-pb-md">
      <div v-if="loading" class="flex flex-center q-py-xl">
        <q-spinner color="violet-normal" size="48px" />
      </div>

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

      <div v-else class="row q-col-gutter-md">
        <div
          v-for="partner in filteredPartners"
          :key="partner.id"
          class="col-12 col-sm-6 col-md-4"
        >
          <q-card flat class="partner-card full-height cursor-pointer" @click="openPartnerDetail(partner)">
            <div class="partner-card__logo-wrap">
              <img
                v-if="partner.logo?.url"
                :src="partner.logo.url"
                class="partner-card__logo-img"
              />
              <div v-else class="partner-card__logo-placeholder">
                <q-icon name="mdi-store-outline" size="48px" color="grey-4" />
              </div>
            </div>

            <q-card-section class="q-pt-sm">
              <div class="row items-start justify-between no-wrap q-mb-xs">
                <div class="text-subtitle2 text-weight-bold partner-card__name ellipsis" style="max-width: 65%">
                  {{ partner.company_name }}
                </div>
                <q-chip
                  v-if="partner.category?.name"
                  dense
                  class="partner-card__category-chip q-ma-none"
                >
                  {{ partner.category.name }}
                </q-chip>
                <div v-if="partner.discount_percentage" class="partner-card__discount-badge">
                  {{ $t('associado.discount') }} -{{ partner.discount_percentage }}%
                </div>
              </div>

              <div v-if="partner.address" class="text-caption partner-card__info row items-center q-mb-xs">
                <q-icon name="mdi-map-marker-outline" size="14px" class="q-mr-xs" />
                {{ partner.address }}<span v-if="partner.neighborhood">, {{ partner.neighborhood }}</span>
              </div>

              <div v-if="partner.phone" class="text-caption partner-card__info row items-center q-mb-xs">
                <q-icon name="mdi-phone-outline" size="14px" class="q-mr-xs" />
                {{ partner.phone }}
              </div>

              <div class="row items-center justify-between q-mt-sm">
                <div class="row items-center text-caption partner-card__info">
                  <q-icon name="mdi-star" size="14px" color="amber" class="q-mr-xs" />
                  <span>—</span>
                </div>
                <div v-if="partner.contract_end" class="text-caption partner-card__info">
                  <q-icon name="mdi-calendar-outline" size="13px" class="q-mr-xs" />
                  {{ $t('associado.validity_until') }} {{ formatDate(partner.contract_end) }}
                </div>
              </div>
            </q-card-section>
          </q-card>
        </div>
      </div>
    </div>

    <q-dialog v-model="detailDialog">
      <q-card style="width: 500px; max-width: 95vw">
        <DefaultDialogHeader
          :title="() => selectedPartner?.company_name || ''"
          @close="detailDialog = false"
        />
        <q-card-section>
          <div class="text-subtitle2 q-mb-sm">{{ $t("associado.services") }}</div>
          <q-list v-if="selectedPartner?.services?.length > 0" separator>
            <q-item v-for="service in selectedPartner.services" :key="service.id">
              <q-item-section>
                <q-item-label>{{ service.name }}</q-item-label>
                <q-item-label caption>{{ service.description }}</q-item-label>
              </q-item-section>
              <q-item-section side>
                <q-item-label v-if="service.discount_percent" class="text-positive">
                  {{ service.discount_percent }}% off
                </q-item-label>
              </q-item-section>
            </q-item>
          </q-list>
          <div v-else class="text-grey text-center q-py-sm">
            {{ $t("http.errors.no_records_found") }}
          </div>
        </q-card-section>
      </q-card>
    </q-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { getConvenios } from "src/api/partnerAgreement";
import { getCategories } from "src/api/category";
import { normalizeString } from "src/helpers/utils";
import { date } from "quasar";

import DefaultHeaderPage from "src/components/layout/DefaultHeaderPage.vue";
import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";

const partners = ref([]);
const categories = ref([]);
const loading = ref(true);
const search = ref("");
const selectedCategory = ref(null);
const detailDialog = ref(false);
const selectedPartner = ref(null);

const formatDate = (d) => d ? date.formatDate(d, "MM/YYYY") : "—";

const filteredPartners = computed(() => {
  let list = partners.value;
  if (selectedCategory.value) {
    list = list.filter((p) => p.category_id === selectedCategory.value);
  }
  if (search.value) {
    const needle = normalizeString(search.value);
    list = list.filter((p) =>
      normalizeString(p.company_name || "").includes(needle),
    );
  }
  return list;
});

const openPartnerDetail = (partner) => {
  selectedPartner.value = partner;
  detailDialog.value = true;
};

onMounted(async () => {
  try {
    const [partnerList, categoryList] = await Promise.all([
      getConvenios(),
      getCategories("partner"),
    ]);
    partners.value = partnerList;
    categories.value = categoryList.map((c) => ({ label: c.name, value: c.id }));
  } catch (e) {
    console.error(e);
  } finally {
    loading.value = false;
  }
});
</script>

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

.convenios-page {
  background: #f3eaf7;
  min-height: 100vh; // item 1: fundo ocupa a página toda

  &__search-input {
    max-width: 700px;
    width: 100%;
  }

  &__chips {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
  }

  &__chip {
    margin: 0;
  }
}

.partner-card {
  border-radius: 12px;
  background: white;
  transition: box-shadow 0.2s;

  &:hover {
    box-shadow: 0 4px 20px rgba(102, 29, 117, 0.15);
  }

  &__logo-wrap {
    height: 150px;
    border-radius: 12px 12px 0 0;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 8px;
  }

  &__logo-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 8px; // arredonda junto com o padding
  }

  &__logo-placeholder {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
  }

  // item 2: desconto no lugar onde estava a categoria (canto inferior direito da imagem)
  &__discount-badge {
    // bottom: 12px;
    // right: 12px;
    background: #661d75;
    color: white;
    font-size: 11px;
    font-weight: 600;
    padding: 3px 10px;
    border-radius: 20px;
  }

  // item 4: textos de info em roxo
  &__name {
    color: #661d75;
  }

  &__info {
    color: #661d75;
    opacity: 0.75;
  }

  // item 3: chip de categoria roxo claro / texto roxo escuro
  &__category-chip {
    background: #ead5f0 !important;
    color: #661d75 !important;
    font-size: 11px;
    font-weight: 500;
    height: 22px;
  }
}
</style>
