<template>
  <div>
    <teleport
      v-if="isMobile && isSummary" to="footer"
    >
      <UPageCard
        class="pay-block--mobile"
        variant="ghost"
        :ui="{
          body: 'w-full',
          footer: 'hidden',
        }"
      >
        <template #body>
          <div class="d-flex flex-row">
            <div>
              <div v-if="cartSum">
                <ProductPrice :is-headline="false" :price="cartSum" />
              </div>
              <div>{{ `${cart?.line_items?.length} шт` }}</div>
            </div>

            <UButton
              class="justify-center text-center w-full ml10"
              size="xl"
              :label="pay ? 'оформить заказ' : 'перейти к оформлению'"
              @click="pay ? createOrder() : router.push(`/checkout/delivery`)"
            />
          </div>
        </template>
      </UPageCard>
    </teleport>

    <UPageCard v-else>
      <template #body>
        <div>товары {{ `(${cart?.line_items?.length} шт)` }}</div>
        <div v-if="cartSum">
          <ProductPrice :is-headline="false" text="итого" :price="cartSum" />
        </div>
      </template>

      <template #footer>
        <UButton
          class="justify-center text-center w-2xs"
          size="xl"
          :label="pay ? 'оформить заказ' : 'перейти к оформлению'"
          @click="pay ? createOrder() : router.push(`/checkout/delivery`)"
        />
      </template>
    </UPageCard>
  </div>
</template>

<script setup lang="ts">
import type { BsbpCreateResponse } from '#shared/bsbp_create'
import { useMediaQuery } from '@vueuse/core'

defineProps({
  pay: {
    type: Boolean,
    default: false,
  },
  isSummary: {
    type: Boolean,
    default: false,
  },
})

const router = useRouter()
const isMobile = useMediaQuery('(max-width: 1280px)', {
  ssrWidth: 768,
})
const { cart, cartSum } = useCart()

const createOrder = async () => {
  const { data } = await useFetch<BsbpCreateResponse>('/api/bsbp_create', {
    method: 'POST',
    body: {
      order: {
        typeRid: 'Purchase',
        amount: cartSum,
        currency: 'RUB',
        hppRedirectUrl: `${process.env.VITE_BASE_URL}/cart`,
      },
    },
  })

  const redirectUrl = `${data?.value?.order?.hppUrl}?orderId=${data?.value?.order?.id}&password=${data.value?.order?.password}`
  window.open(redirectUrl, '_blank')
}
</script>

<style lang="scss">
.pay-block {
  &--mobile {
    position: sticky;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 100;
  }
}
</style>
