<template>
  <UContainer>
    <UButton size="xl" label="btn" />

    <div class="card">
      <div class="card__images">
        <div
          v-for="image in currentVariantImages"
          :key="image?.id"
        >
          <img width="100%" :src="image?.src" :alt="image?.src">
        </div>
      </div>

      <div class="card__description">
        <h1>{{ productsData?.name }}</h1>

        Цена
        {{ currentVariant?.price }}

        Коротокое описание
        {{ productsData?.short_description }}

        <div class="card__variation">
          <div
            v-for="variation in productsVariationsData"
            :key="variation?.id"
            @click="() => currentVariantId = variation?.id"
          >
            {{ variation?.id }}
            <img width="200px" :src="variation?.image?.src" :alt="variation?.image?.src">
          </div>
        </div>

        <pre>
        {{ currentVariant }}
      </pre>
      </div>
    </div>
  </UContainer>
</template>

<script setup lang="ts">
import { useGetProductsDetail, useGetProductsVariationsList } from '~/api/queries'

// Вынести все computed в composable useProduct.ts
const { data: productsData } = useGetProductsDetail(79)
const { data: productsVariationsData } = useGetProductsVariationsList(79)

function getAttribute(attributes, name: string) {
  return attributes?.find(attribute => attribute?.name === name)?.option
}

const defaultColor = computed(() => getAttribute(productsData?.value?.default_attributes, 'color'))
const defaultMaterial = computed(() => getAttribute(productsData?.value?.default_attributes, 'material'))

const defaultVariant = computed(() => {
  return productsVariationsData?.value?.find(variation => getAttribute(variation?.attributes, 'color') === defaultColor?.value)
    && productsVariationsData?.value?.find(variation => getAttribute(variation?.attributes, 'material') === defaultMaterial?.value)
})

const currentVariantId = ref(defaultVariant?.value?.id)

const currentVariant = computed(() => productsVariationsData?.value?.find(variation => variation?.id === currentVariantId?.value))

const currentColor = computed(() => getAttribute(currentVariant?.value?.attributes, 'color'))
const currentMaterial = computed(() => getAttribute(currentVariant?.value?.attributes, 'material'))

const currentVariantImages
    = computed(() => productsData?.value?.images
      ?.filter(img => img?.src?.includes(`${currentColor.value}_${currentMaterial.value}_`)))

watch(() => defaultVariant.value, newValue => currentVariantId.value = newValue?.id)
</script>

<style lang="scss">
.card {
  width: 100%;
  display: flex;
  flex-direction: row;

  &__images {
    width: 100%;
    display: flex;
    flex-direction: column;
  }

  &__description {
    padding-inline: 30px;
    width: 40%;
  }

  &__variation {
    display: flex;
    flex-direction: row;
    gap: 10px;
  }
}
</style>
