<template>
  <div>
    <DefaultHeaderPage>
      <template #after>
        <div class="flex gap-sm q-mt-md">
          <q-btn
            unelevated
            class="btn-gradient"
            :label="$t('common.actions.new')"
            icon="mdi-plus"
            padding="8px 12px"
            @click="onAddItem"
          />
        </div>
      </template>
    </DefaultHeaderPage>

    <div class="q-pa-md">
      <div class="row q-col-gutter-sm q-mb-md">
        <div class="col-12 col-md-5">
          <q-input
            v-model="search"
            :placeholder="$t('common.actions.search')"
            outlined
            dense
            clearable
          >
            <template #prepend>
              <q-icon name="mdi-magnify" />
            </template>
          </q-input>
        </div>
      </div>

      <div class="row q-gutter-xs q-mb-md flex-wrap">
        <div
          :class="['cat-chip', activeTab === 'all' ? 'cat-chip--selected' : 'cat-chip--default']"
          @click="activeTab = 'all'"
        >
          {{ $t('loja.filter_all') }}
        </div>
        <div
          v-for="cat in storeCategories"
          :key="cat.value"
          :class="['cat-chip', activeTab === cat.value ? 'cat-chip--selected' : 'cat-chip--default']"
          @click="activeTab = cat.value"
        >
          {{ cat.label }}
        </div>
        <div
          :class="['cat-chip', activeTab === 'recent' ? 'cat-chip--selected' : 'cat-chip--default']"
          @click="activeTab = 'recent'"
        >
          {{ $t('loja.filter_recent') }}
        </div>
        <div class="cat-chip cat-chip--disabled">
          {{ $t('loja.filter_others') }}
        </div>
      </div>
      <div v-if="loading" class="flex flex-center q-py-xl">
        <q-spinner color="primary" size="48px" />
      </div>

      <div v-else-if="filteredItems.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 items-stretch">
        <div
          v-for="item in filteredItems"
          :key="item.id"
          class="col-12 col-sm-6 col-md-4"
        >
          <q-card flat bordered class="store-card" style="height: 100%">
            <q-card-section class="q-pa-sm col column" style="height: 100%">
              <div class="row no-wrap store-card-inner" style="flex: 1">
                <div class="col column justify-between q-pr-sm">
                  <div class="row items-center justify-between no-wrap q-mb-xs">
                    <div class="row items-center q-gutter-xs flex-wrap">
                      <span v-if="item.category?.name" class="badge-category">
                        {{ item.category.name }}
                      </span>
                      <span :class="isActive(item) ? 'badge-active' : 'badge-inactive'">
                        {{ isActive(item) ? $t('common.status.active') : $t('common.status.inactive') }}
                      </span>
                    </div>
                    <div class="row no-wrap items-center" style="gap: 2px">
                      <q-btn
                        flat round dense size="sm"
                        color="negative"
                        icon="mdi-pause-circle-outline"
                        @click="onSetStatus(item, 'inactive')"
                      />
                      <q-btn
                        flat round dense size="sm"
                        color="positive"
                        icon="mdi-play-circle-outline"
                        @click="onSetStatus(item, 'active')"
                      />
                      <q-btn
                        flat round dense size="sm"
                        class="btn-edit-icon"
                        icon="mdi-pencil"
                        @click="onEdit(item)"
                      />
                    </div>
                  </div>
                  <div class="text-subtitle1 text-weight-medium text-violet-medium q-mb-xs leading-tight">
                    {{ item.name }}
                  </div>

                  <div v-if="item.description" class="text-caption text-grey-7 q-mb-sm ellipsis-2-lines">
                    {{ item.description }}
                  </div>

                  <template v-if="item.variations?.length">
                    <div class="text-caption text-grey-6 q-mb-xs">
                      {{ variationTypeLabel(item) }}
                    </div>
                    <div class="row justify-end q-gutter-xs q-mb-sm">
                      <div
                        v-for="v in item.variations"
                        :key="v.id"
                        :class="['variation-tag', activeVariation(item)?.id === v.id ? 'variation-tag--selected' : 'variation-tag--default']"
                        @click="selectVariation(item, v)"
                      >
                        {{ v.variation_label }}
                      </div>
                    </div>
                  </template>

                  <div class="row items-end justify-between q-mt-sm">
                    <div class="column" style="gap: 1px">
                      <span class="text-caption text-grey-6">
                        {{ $t('loja.stock') }}: {{ displayStock(item) }}
                      </span>
                      <span class="text-caption text-grey-6">
                        {{ $t('loja.interests') }}: {{ item.interests_count ?? 0 }}
                      </span>
                    </div>
                    <div class="column items-end" style="gap: 1px">
                      <span v-if="item.price" class="text-caption text-grey-5 text-strike">
                        R$ {{ formatPrice(item.price) }}
                      </span>
                      <span v-if="displayPrice(item) != null" class="text-subtitle2 text-weight-bold text-violet-dark">
                        R$ {{ formatPrice(displayPrice(item)) }}
                      </span>
                    </div>
                  </div>
                </div>

                <div class="store-card-right column items-stretch no-wrap">
                  <div class="store-card-image col">
                    <img
                      v-if="item.media?.length"
                      :src="item.media[0].url"
                      :alt="item.name"
                      class="store-card-img"
                    />
                    <q-icon
                      v-else
                      name="mdi-image-off-outline"
                      size="32px"
                      color="grey-4"
                      class="absolute-center"
                    />
                  </div>
                  <q-btn
                    unelevated
                    size="sm"
                    class="btn-gradient q-mt-xs"
                    :label="$t('loja.interested_btn')"
                    icon="mdi-thumb-up"
                    padding="5px 8px"
                    style="width: 100%"
                    @click="onInterests(item)"
                  />
                </div>

              </div>
            </q-card-section>
          </q-card>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import { ref, computed, onMounted, defineAsyncComponent } from "vue";
import { useRouter } from "vue-router";
import { useQuasar } from "quasar";
import { useI18n } from "vue-i18n";
import { permissionStore } from "src/stores/permission";
import { getStoreItems, toggleStoreItemStatus } from "src/api/storeItem";
import { getCategories } from "src/api/category";
import { normalizeString } from "src/helpers/utils";
import DefaultHeaderPage from "src/components/layout/DefaultHeaderPage.vue";

const StoreItemInterestsDialog = defineAsyncComponent(
  () => import("./components/StoreItemInterestsDialog.vue"),
);

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

const items = ref([]);
const loading = ref(true);
const search = ref("");
const activeTab = ref("all");
const storeCategories = ref([]);

const selectedVariations = ref({});

const selectVariation = (item, variation) => {
  selectedVariations.value[item.id] = variation;
};

const activeVariation = (item) => selectedVariations.value[item.id] ?? null;

const displayPrice = (item) => {
  const v = activeVariation(item);
  if (v && v.variation_value != null) return v.variation_value;
  return item.associate_price;
};

const displayStock = (item) => {
  const v = activeVariation(item);
  if (v) return v.stock ?? 0;
  return item.stock ?? 0;
};

const filteredItems = computed(() => {
  let list = items.value;

  if (activeTab.value === "recent") {
    const dateToCompare = new Date().setDate(new Date().getDate() - 30);
    list = list.filter((i) => new Date(i.created_at).getTime() >= dateToCompare);
  } else if (activeTab.value !== "all") {
    list = list.filter((i) => i.category_id === activeTab.value);
  }

  if (search.value) {
    const needle = normalizeString(search.value);
    list = list.filter((i) => normalizeString(i.name || "").includes(needle));
  }

  return list;
});

const isActive = (item) =>
  item.status?.value === "active" || item.status === "active";

const variationTypeLabel = (item) => {
  const type = item.variations?.[0]?.variation_type;
  if (type === "tamanho") return t("loja.variation_tamanho");
  if (type === "cor")     return t("loja.variation_cor");
  if (type === "modelo")  return t("loja.variation_modelo");
  return "";
};

const formatPrice = (price) =>
  Number(price).toLocaleString("pt-BR", { minimumFractionDigits: 2 });

onMounted(async () => {
  try {
    const [itemsData, catsData] = await Promise.all([
      getStoreItems(),
      getCategories("store"),
    ]);
    items.value = itemsData;
    storeCategories.value = catsData.map((c) => ({ label: c.name, value: c.id }));

    itemsData.forEach((item) => {
      if (item.variations?.length) {
        selectedVariations.value[item.id] = item.variations ?? item.variations[0];
      }
    });
  } catch (e) {
    console.error(e);
  } finally {
    loading.value = false;
  }
});

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

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

const onSetStatus = async (item) => {
  if (!permission_store.getAccess("loja.item", "edit")) {
    $q.notify({ type: "negative", message: t("validation.permissions.edit") });
    return;
  }
  try {
    const updated = await toggleStoreItemStatus(item.id);
    const idx = items.value.findIndex((i) => i.id === item.id);
    if (idx !== -1) items.value[idx] = { ...items.value[idx], ...updated };
    $q.notify({ type: "positive", message: t("http.success") });
  } catch {
    $q.notify({ type: "negative", message: t("http.errors.failed") });
  }
};


const onInterests = (item) => {
  $q.dialog({
    component: StoreItemInterestsDialog,
    componentProps: {
      storeItemId: item.id,
      storeItemName: item.name,
    },
  });
};
</script>

<style lang="scss" scoped>
.store-card {
  transition: box-shadow 0.2s;
  display: flex;
  flex-direction: column;
  &:hover { box-shadow: 0 4px 16px rgba(102, 29, 117, 0.12); }
}

.store-card-inner {
  min-height: 0;
  flex: 1;
}

.store-card-right {
  width: 110px;
  min-width: 110px;
  flex-shrink: 0;
}

.store-card-image {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid rgba(102, 29, 117, 0.15);
  background: #f5f0f7;
  min-height: 110px;
}

.store-card-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.ellipsis-2-lines {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.category-tabs {
  :deep(.q-tab__label) { font-size: 13px; }
}

// --- category chips ---
.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;

  &--default {
    background: #c9a3dc;
    color: #fff;
  }

  &--selected {
    background: #4d1658;
    color: #fff;
  }

  &--disabled {
    background: #c9a3dc;
    color: rgba(255,255,255,0.5);
    cursor: default;
    pointer-events: none;
  }
}

// --- badges ---
.badge-category {
  display: inline-flex;
  align-items: center;
  background: #ede0f5;
  color: #4d1658;
  font-size: 10px;
  font-weight: 500;
  padding: 2px 8px;
  border-radius: 20px;
  line-height: 1.4;
}

.badge-active {
  display: inline-flex;
  align-items: center;
  background: #22c55e;
  color: #fff;
  font-size: 10px;
  font-weight: 500;
  padding: 2px 8px;
  border-radius: 20px;
  line-height: 1.4;
}

.badge-inactive {
  display: inline-flex;
  align-items: center;
  background: #eab308;
  color: #fff;
  font-size: 10px;
  font-weight: 500;
  padding: 2px 8px;
  border-radius: 20px;
  line-height: 1.4;
}

// --- variation tags ---
.variation-tag {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 28px;
  height: 26px;
  padding: 0 7px;
  border-radius: 4px;
  font-size: 11px;
  font-weight: 500;
  cursor: pointer;
  user-select: none;
  transition: background 0.15s, color 0.15s;

  &--default {
    background: #ede0f5;
    color: #4d1658;
  }

  &--selected {
    background: #4d1658;
    color: #ede0f5;
  }
}

.gap-sm { gap: 8px; }

.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; }

.btn-edit-icon {
  background: linear-gradient(90deg, #4d1658 0%, #8b30a5 100%) !important;
  color: white !important;
  border-radius: 6px !important;
  width: 28px;
  height: 28px;
}

.btn-edit-icon :deep(.q-icon) { color: white !important; }

.text-violet-dark   { color: #4d1658; }
.text-violet-medium { color: #7b2d97; }

.leading-tight { line-height: 1.25; }
</style>
