<template>
  <div
    class="barneo-products-widget"
    :class="{
      'barneo-products-widget--dark': mergedConfig.darkMode === true,
      'barneo-products-widget--light': mergedConfig.darkMode === false,
    }"
  >
    <slot
      name="products-grid"
      :products="sharedState.searchState.full_products"
      :is-loading="isSharedLoading"
      :item-width="itemWidth"
    >
      <slot name="loading" :is-loading="showSkeleton">
        <div v-if="showSkeleton" class="barneo-products-loading">
          <BarneoProductsSkeleton
            :count="mergedConfig.itemsPerPage"
            :item-width="itemWidth"
          />
        </div>
      </slot>

      <div v-if="showProductsList" class="barneo-products-container">
        <AdaptiveGrid :item-width="itemWidth">
          <slot
            v-for="(product, index) in sharedState.searchState.full_products"
            :key="product.id || index"
            name="product-card"
            :product="product"
            :index="index"
            :on-select="(product: any, event?: MouseEvent) => handleProductSelect(product, event)"
            :handle-aux-click="(product: any, event: MouseEvent) => handleAuxClick(product, event)"
            @mousedown.prevent
          >
            <div
              class="barneo-product-card"
              @click="(event) => handleProductSelect(product, event)"
              @auxclick="(event) => handleAuxClick(product, event)"
              @mousedown.prevent
            >
              <!-- Верхний блок с border -->
              <div class="barneo-product-top">
                <!-- Метаданные и кнопка избранного -->
                <slot
                  name="product-header"
                  :product="product"
                  :is-in-favourites="isInFavourites(Number(product.id))"
                  :toggle-favourite="() => toggleFavourite(Number(product.id))"
                  :copy-text="copyText"
                  :show-favourites="mergedConfig.showFavourites"
                >
                  <div class="barneo-product-header">
                    <slot
                      name="product-metadata"
                      :product="product"
                      :copy-text="copyText"
                    >
                      <div class="barneo-product-metadata">
                        <div
                          v-if="product.properties?.[0]?.values?.[0]?.value"
                          class="barneo-product-code"
                          @click.stop="
                            copyText(product.properties?.[0]?.values?.[0]?.value)
                          "
                        >
                          Код: {{ product.properties?.[0]?.values?.[0]?.value }}
                        </div>
                        <div
                          v-if="product.vendor_code"
                          class="barneo-product-article"
                          @click.stop="copyText(product.vendor_code)"
                        >
                          Артикул: {{ product.vendor_code }}
                        </div>
                      </div>
                    </slot>

                    <!-- Heart Icon -->
                    <slot
                      name="product-favourites"
                      :product="product"
                      :is-in-favourites="isInFavourites(Number(product.id))"
                      :toggle-favourite="() => toggleFavourite(Number(product.id))"
                      :show-favourites="mergedConfig.showFavourites"
                    >
                      <div
                        v-if="mergedConfig.showFavourites"
                        class="barneo-product-heart"
                        :class="{
                          'is-in-favourites': isInFavourites(Number(product.id)),
                        }"
                        @click.stop="toggleFavourite(Number(product.id))"
                      >
                        <svg viewBox="0 0 24 24" fill="currentColor">
                          <path
                            d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"
                          />
                        </svg>
                      </div>
                    </slot>
                  </div>
                </slot>

                <!-- Product Image -->
                <slot
                  name="product-image"
                  :product="product"
                  :handle-image-error="handleImageError"
                >
                  <div class="barneo-product-image">
                    <img
                      v-if="product.picture"
                      :src="product.picture"
                      :alt="product.name"
                      @error="handleImageError"
                    />
                    <div v-else class="barneo-product-image-placeholder">📦</div>
                  </div>
                </slot>
              </div>

              <!-- Нижний блок без border -->
              <div class="barneo-product-bottom">
                <!-- Первый подблок: цена, бренд, тег -->
                <slot
                  name="product-info"
                  :product="product"
                  :format-price="formatPrice"
                >
                  <div class="barneo-product-info">
                    <!-- Price -->
                    <slot
                      name="product-price"
                      :product="product"
                      :format-price="formatPrice"
                    >
                      <div v-if="product.price" class="barneo-product-price">
                        {{ formatPrice(product.price) }}
                      </div>
                    </slot>

                    <!-- Brand with Checkmark -->
                    <slot name="product-brand" :product="product">
                      <div v-if="true" class="barneo-product-brand">
                        <span>Бренд</span>
                        <svg
                          class="barneo-product-brand-checkmark"
                          viewBox="0 0 16.1543 16.0029"
                          fill="none"
                        >
                          <path
                            d="M16.05 8.86L15 7.15L15.53 5.21C15.6 4.9 15.46 4.58 15.17 4.44L13.37 3.56L12.75 1.65C12.66 1.34 12.35 1.16 12.04 1.19L10.05 1.43L8.5 0.15C8.25 -0.06 7.89 -0.06 7.65 0.15L6.1 1.43L4.1 1.19C3.79 1.16 3.49 1.34 3.39 1.65L2.78 3.56L0.97 4.44C0.68 4.58 0.54 4.9 0.62 5.21L1.14 7.15L0.09 8.86C-0.08 9.14 -0.02 9.49 0.21 9.71L1.7 11.06L1.75 13.06C1.76 13.38 1.99 13.66 2.31 13.71L4.29 14.04L5.41 15.7C5.59 15.97 5.93 16.07 6.23 15.94L8.07 15.15L9.92 15.94C10 15.98 10.09 16 10.18 16C10.4 16 10.6 15.89 10.73 15.7L11.86 14.04L13.84 13.71C14.15 13.66 14.39 13.38 14.4 13.06L14.45 11.06L15.93 9.71C16.16 9.49 16.22 9.14 16.05 8.86ZM10.97 6.96L8.01 10.39C7.88 10.54 7.69 10.62 7.5 10.62C7.36 10.62 7.22 10.57 7.09 10.48L5.03 8.87C4.74 8.65 4.69 8.23 4.91 7.94C5.14 7.65 5.56 7.59 5.85 7.82L7.41 9.04L9.96 6.09C10.2 5.81 10.62 5.78 10.9 6.02C11.18 6.26 11.21 6.68 10.97 6.96Z"
                            fill="currentColor"
                          />
                        </svg>
                      </div>
                    </slot>

                    <!-- Availability -->
                    <slot
                      name="product-availability"
                      :product="product"
                      :is-in-stock="product.price >= 1"
                    >
                      <div
                        v-if="product.price !== undefined"
                        class="barneo-product-availability"
                        :class="{
                          'barneo-product-availability--in-stock':
                            product.price >= 1,
                          'barneo-product-availability--out-of-stock':
                            product.price < 1,
                        }"
                      >
                        {{ product.price >= 1 ? "В наличии" : "Нет в наличии" }}
                      </div>
                    </slot>
                  </div>
                </slot>

                <!-- Второй подблок: название, доставка, кнопка -->
                <slot
                  name="product-actions"
                  :product="product"
                  :add-to-cart="() => addToCart(product)"
                  :is-disabled="product.price === 0"
                >
                  <div class="barneo-product-actions">
                    <!-- Product Title -->
                    <slot name="product-title" :product="product">
                      <h3 class="barneo-product-title">{{ product.name }}</h3>
                    </slot>

                    <!-- Delivery Info -->
                    <slot name="product-delivery" :product="product">
                      <div class="barneo-product-delivery">Бесплатная доставка</div>
                    </slot>

                    <!-- Add to Cart Button -->
                    <slot
                      name="product-add-to-cart"
                      :product="product"
                      :add-to-cart="() => addToCart(product)"
                      :is-disabled="product.price === 0"
                    >
                      <button
                        class="barneo-product-add-to-cart"
                        :disabled="product.price === 0"
                        @click.stop="addToCart(product)"
                      >
                        В корзину
                      </button>
                    </slot>
                  </div>
                </slot>
              </div>
            </div>
          </slot>
        </AdaptiveGrid>
      </div>
    </slot>

    <slot
      name="products-empty"
      :is-loading="showEmptyState"
      :has-products="sharedState.searchState.full_products.length > 0"
      :query="sharedState.searchState.query"
    >
      <div v-if="showEmptyState" class="barneo-products-empty">
        <p>🔍 Товары не найдены</p>
        <p v-if="sharedState.searchState.query">
          По запросу "{{ sharedState.searchState.query }}" ничего не найдено
        </p>
      </div>
    </slot>

    <slot
      name="products-pagination"
      :pagination="pagination"
      :on-page-change="handlePageChange"
    >
      <div
        v-if="mergedConfig.showPagination && pagination.totalPages > 1"
        class="barneo-products-pagination"
      >

        <button
          :disabled="pagination.currentPage === 1"
          @click="handlePageChange(pagination.currentPage - 1)"
          class="barneo-pagination-button barneo-pagination-button--prev"
        >
          <svg viewBox="0 0 24 24" fill="currentColor" width="24" height="24">
            <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z" />
          </svg>
        </button>

        <div class="barneo-pagination-pages">
          <button
            v-for="page in visiblePages"
            :key="page"
            :class="{
              'barneo-pagination-page': true,
              'barneo-pagination-page--active': page === pagination.currentPage,
            }"
            @click="handlePageChange(page)"
          >
            {{ page }}
          </button>
        </div>

        <button
          :disabled="pagination.currentPage === pagination.totalPages"
          @click="handlePageChange(pagination.currentPage + 1)"
          class="barneo-pagination-button barneo-pagination-button--next"
        >
          <svg viewBox="0 0 24 24" fill="currentColor" width="24" height="24">
            <path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z" />
          </svg>
        </button>

        <slot
          name="products-total-count"
          :total-count="sharedState.searchState.totalProducts"
          :show-total-count="mergedConfig.showTotalCount"
        >
          <div
            v-if="mergedConfig.showTotalCount && sharedState.searchState.totalProducts"
            class="barneo-products-total-count"
          >
            Найдено товаров: {{ sharedState.searchState.totalProducts }}
          </div>
        </slot>
      </div>

    </slot>


    <slot name="error" :error="error">
      <div v-if="error" class="barneo-products-error">
        <span>❌ {{ error }}</span>
      </div>
    </slot>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import type { BarneoProductsWidgetProps, ProductsWidgetEmits } from "../types";
import { useProductsWidget } from "../composables/useProductsWidget";
import { useSharedState } from "../../sharedState/composables/useSharedState";
import { useBarneoConfig } from "../../../config/BarneoConfigManager";
import AdaptiveGrid from "./AdaptiveGrid.vue";
import BarneoProductsSkeleton from "./BarneoProductsSkeleton.vue";

const props = withDefaults(defineProps<BarneoProductsWidgetProps>(), {
  config: () => ({}),
  products: () => [],
  loading: false,
  error: null,
  pagination: () => ({
    currentPage: 1,
    totalPages: 0,
    totalProducts: 0,
    itemsPerPage: 20,
    offset: 0,
  }),
});

const emit = defineEmits<ProductsWidgetEmits>();

const { productsWidgetConfig, apiService: globalApiService } =
  useBarneoConfig();
const sharedState = useSharedState();
const { searchState } = sharedState;

const mergedConfig = computed(() => ({
  itemsPerPage: 20,
  mobileItemWidth: 140,
  desktopItemWidth: 250,
  darkMode: false,
  showPagination: true,
  showTotalCount: true,
  showFavourites: true,
  ...productsWidgetConfig,
  ...props.config,
}));

const apiService = props.apiService || globalApiService;

const {
  isLoading,
  error,
  pagination,
  loadProducts,
  handlePageChange,
  handleProductSelect,
} = useProductsWidget(mergedConfig.value, apiService, emit);

const isSharedLoading = computed(() => {
  return sharedState.searchState.isLoading;
});

const showSkeleton = computed(() => {
  return isSharedLoading.value;
});

const showProductsList = computed(() => {
  return (
    !isSharedLoading.value && sharedState.searchState.full_products.length > 0
  );
});

const showEmptyState = computed(() => {
  return (
    !isSharedLoading.value &&
    sharedState.searchState.full_products.length === 0 &&
    sharedState.searchState.query
  );
});

const isMobile = ref(false);

const updateScreenSize = () => {
  isMobile.value = window.innerWidth < 768;
};

const itemWidth = computed(() =>
  isMobile.value
    ? mergedConfig.value.mobileItemWidth
    : mergedConfig.value.desktopItemWidth
);

const visiblePages = computed(() => {
  const { currentPage, totalPages } = pagination.value;
  const maxVisible = 5;
  const halfVisible = Math.floor(maxVisible / 2);

  let start = Math.max(1, currentPage - halfVisible);
  let end = Math.min(totalPages, start + maxVisible - 1);

  if (end - start + 1 < maxVisible) {
    start = Math.max(1, end - maxVisible + 1);
  }

  return Array.from({ length: end - start + 1 }, (_, i) => start + i);
});

const formatPrice = (price: number): string => {
  const priceInRubles = price / 100;

  return new Intl.NumberFormat("ru-RU", {
    style: "currency",
    currency: "RUB",
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  }).format(priceInRubles);
};

const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement;
  img.style.display = "none";
  img.nextElementSibling?.classList.remove("barneo-product-image-placeholder");
};

const favourites = ref<Set<number>>(new Set());

const isInFavourites = (productId: number): boolean => {
  return favourites.value.has(productId);
};

const toggleFavourite = (productId: number) => {
  const product = sharedState.searchState.full_products.find(
    (p) => Number(p.id) === productId
  );

  if (!product) return;

  if (favourites.value.has(productId)) {
    favourites.value.delete(productId);
    // @ts-ignore
    emit("remove-from-favourites", product);
  } else {
    favourites.value.add(productId);
    // @ts-ignore
    emit("add-to-favourites", product);
  }
};

const copyText = (text: string) => {
  navigator.clipboard
    .writeText(text)
    .then(() => {
      emit("text-copied", text);
    })
    .catch((error) => {
      console.error("Ошибка при копировании:", error);
    });
};

const addToCart = (product: any) => {
  emit("add-to-cart", product);
};

// Обработчик auxclick для средней кнопки мыши
const handleAuxClick = (product: any, event: MouseEvent) => {
  // Используем ту же логику, что и handleProductSelect, но с принудительным event
  handleProductSelect(product, event);
};

onMounted(() => {
  updateScreenSize();
  window.addEventListener("resize", updateScreenSize);
});

defineExpose({
  loadProducts,
  handlePageChange,
  handleProductSelect,
});
</script>
