<script setup lang="ts">
import { InputNumber } from '~/src/shared/ui'
import type { CrmProduct } from '~/src/shared/model'

const props = defineProps<{
  product: CrmProduct
}>()

const amount = ref(0)
const currentUnitPrice = ref(0)
const prevUnitPrice = ref()

function updatePrices() {
  if (!props.product.variants?.length) {
    return
  }

  for (let i = 0; i < props.product.variants.length; i++) {
    const variant = props.product.variants[i]

    let max = Number.POSITIVE_INFINITY
    let min = 0

    variant.properties?.forEach((property) => {
      if (property.name === 'min') {
        min = Number(property.value)
      }

      if (property.name === 'max')
        max = Number(property.value)
    })

    if (amount.value >= min && amount.value <= max) {
      currentUnitPrice.value = Number(variant.price) / 100

      if (i !== 0) {
        prevUnitPrice.value = Number(props.product.variants[i - 1].price) / 100
      }
      else {
        prevUnitPrice.value = undefined
      }

      return
    }
  }
}

updatePrices()
</script>

<template>
  <div class="w-64 flex flex-col border-1 rounded-[20px]">
    <div class="h-64 relative flex flex-col justify-between rounded-t-[20px]">
      <img alt="product_img" :src="`https://cake-crm.3crabs.ru${product.images?.[0]}`" class="rounded-t-[20px]">

      <div class="flex gap-1 absolute top-3 left-3">
        <UBadge v-for="(label, index) in product.labels" :key="index" :ui="{ rounded: 'rounded-full' }" size="md">
          {{ label.name }}
        </UBadge>
      </div>

      <div class="flex justify-end text-slate-500 text-sm absolute bottom-3 right-3">
        {{ currentUnitPrice }} ₽ / {{ product.unit }}
      </div>
    </div>

    <div class="flex flex-col gap-3 p-5">
      <div>{{ product.name }}</div>
      <div class="flex items-center gap-3">
        <div class="text-2xl font-bold" :class="{ 'text-pink-800': prevUnitPrice }">
          {{ currentUnitPrice * (amount || 1) }} ₽
        </div>
        <div v-if="prevUnitPrice" class="line-through text-slate-400">
          {{ prevUnitPrice * amount }} ₽
        </div>
      </div>

      <div class="w-full">
        <UButton v-if="!amount" class="w-full justify-center" size="xl" @click="amount = 1">
          В корзину
        </UButton>
        <InputNumber v-else v-model="amount" @update:model-value="updatePrices" />
      </div>
    </div>
  </div>
</template>
