<template>
    <component :is="Default || 'div'">
  <div class="container mx-auto mt-20 flex flex-col gap-5 md:gap-10">
    <h1 class="text-2xl font-bold text-black dark:text-white">{{ t('Shopping Cart') }}</h1>
    <div class="flex flex-col lg:flex-row gap-5 md:gap-10">
      <div class="flex-1">
        <div
          class="bg-(--second-light) dark:bg-(--main-dark) rounded-lg border border-(--border-light) dark:border-(--border-dark) overflow-hidden">
          <h2
            class="text-lg font-semibold text-black dark:text-white p-4 border-b border-(--border-light) dark:border-(--border-dark)">
            {{ t('Selected Products') }}
          </h2>
          <div v-if="cartStore.items.length > 0">
            <div v-for="item in cartStore.items" :key="item.id"
              class="grid grid-cols-5 items-center p-4 border-b border-(--border-light) dark:border-(--border-dark) w-[100%]">
              <div
                class="bg-(--second-light) dark:bg-(--main-dark) rounded flex items-center justify-center overflow-hidden">
                <img v-if="item.image" :src="item.image" :alt="item.name" class="w-full h-full object-cover" />
                <UIcon v-else name="mdi:package-variant" class="text-2xl text-gray-400" />
              </div>
              <p class="text-black dark:text-white text-sm font-medium">{{ item.name }}</p>
              <p class="text-black dark:text-white">${{ item.price.toFixed(2) }}</p>
              <p class="text-black dark:text-white font-medium">${{ (item.price * item.quantity).toFixed(2)
              }}</p>

              <div class="flex items-center justify-end gap-10">
                <UInputNumber v-model="item.quantity" :min="1"
                  @update:model-value="(val: number) => cartStore.updateQuantity(item.id, val)" />
                <div class="flex justify-center">
                  <button @click="removeItem(item.id)"
                    class="p-2 text-red-500 bg-red-100 dark:bg-(--main-dark)  rounded transition-colors"
                    :title="t('Remove')">
                    <UIcon name="material-symbols:delete" class="text-[20px]" />
                  </button>
                </div>
              </div>
            </div>
          </div>
          <div v-else class="p-8 text-center">
            <UIcon name="mdi:cart-outline" class="text-6xl text-gray-300 dark:text-gray-600 mb-4" />
            <p class="text-gray-500 dark:text-gray-400">{{ t('Your cart is empty') }}</p>
            <RouterLink :to="{ name: 'product-card-full' }"
              class="inline-block mt-4 text-(--accent-blue-light) dark:text-(--accent-blue-dark) hover:underline">
              {{ t('Continue Shopping') }}
            </RouterLink>
          </div>
        </div>
      </div>
      <div class="lg:w-80">
        <div
          class="bg-(--second-light) dark:bg-(--main-dark) rounded-lg border border-(--border-light) dark:border-(--border-dark) p-6 sticky top-24">
          <h2 class="text-lg font-semibold text-black dark:text-white mb-4">{{ t('Order Summary') }}</h2>
          <div class="space-y-3 border-b border-(--border-light) dark:border-(--border-dark) pb-4 mb-4">
            <div class="flex justify-between">
              <span class="text-gray-600 dark:text-gray-400">{{ t('Products total') }}</span>
              <span class="text-black dark:text-white">${{ cartStore.productsTotal.toFixed(2) }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-600 dark:text-gray-400">{{ t('Shipping') }}</span>
              <span class="text-black dark:text-white">
                {{ cartStore.shippingCost > 0 ? `$${cartStore.shippingCost.toFixed(2)}` : t('Free') }}
              </span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-600 dark:text-gray-400">{{ t('VAT') }} ({{ (cartStore.vatRate * 100).toFixed(0)
                }}%)</span>
              <span class="text-black dark:text-white">${{ cartStore.vatAmount.toFixed(2) }}</span>
            </div>
          </div>
          <div class="flex justify-between mb-6">
            <span class="text-black dark:text-white font-semibold text-lg">{{ t('Total') }}</span>
            <span class="text-(--accent-blue-light) dark:text-(--accent-blue-dark) font-bold text-lg">${{
              cartStore.orderTotal.toFixed(2) }}</span>
          </div>
          <div class="flex flex-col gap-3">
            <UButton block color="primary" @click="placeOrder" :disabled="!canPlaceOrder"
              class="bg-(--accent-blue-light) dark:bg-(--accent-blue-dark) text-white hover:bg-(--accent-blue-dark) dark:hover:bg-(--accent-blue-light) disabled:opacity-50 disabled:cursor-not-allowed">
              {{ t('Place Order') }}
            </UButton>
            <UButton block variant="outline" color="neutral" @click="cancelOrder"
              class="text-black dark:text-white border-(--border-light) dark:border-(--border-dark) hover:bg-gray-100 dark:hover:bg-gray-700">
              {{ t('Cancel') }}
            </UButton>
          </div>
        </div>
      </div>
    </div>
    <div class="grid grid-cols-1 md:grid-cols-2 gap-5 md:gap-10">
      <div class="flex-1">
        <div
          class="bg-(--second-light) dark:bg-(--main-dark) rounded-lg border border-(--border-light) dark:border-(--border-dark) p-6">
          <h2 class="text-lg font-semibold text-black dark:text-white mb-4">{{ t('Select Delivery Address') }}</h2>
          <div class="mb-4">
            <UInput v-model="addressSearchQuery" type="text" :placeholder="t('Search address')"
              class="w-full bg-white dark:bg-gray-800 text-black dark:text-white" />
          </div>
          <div v-if="addressStore.filteredAddresses.length > 0" class="space-y-3">
            <label v-for="address in addressStore.filteredAddresses" :key="address.id"
              class="flex items-start gap-3 p-4 border rounded-lg cursor-pointer transition-colors" :class="cartStore.selectedAddressId === address.id
                ? 'border-(--accent-blue-light) dark:border-(--accent-blue-dark) bg-blue-50 dark:bg-blue-900/20'
                : 'border-(--border-light) dark:border-(--border-dark) hover:border-gray-400'">
              <input type="radio" :value="address.id" v-model="selectedAddress"
                class="mt-1 w-4 h-4 text-(--accent-blue-light) dark:text-(--accent-blue-dark)" />
              <div class="flex-1">
                <p class="text-black dark:text-white font-medium">{{ address.street }}</p>
                <p class="text-gray-600 dark:text-gray-400 text-sm">{{ address.zipCode }}, {{ address.city }}</p>
                <p class="text-gray-600 dark:text-gray-400 text-sm">{{ address.country }}</p>
              </div>
            </label>
          </div>
          <div v-else class="text-center py-6">
            <UIcon name="mdi:map-marker-outline" class="text-4xl text-gray-400 mb-2" />
            <p class="text-gray-500 dark:text-gray-400">{{ t('No addresses found') }}</p>
            <RouterLink :to="{ name: 'addresses' }"
              class="inline-block mt-2 text-(--accent-blue-light) dark:text-(--accent-blue-dark) hover:underline">
              {{ t('Add Address') }}
            </RouterLink>
          </div>
        </div>
      </div>
      <div class="flex-1">
        <div
          class="bg-(--second-light) dark:bg-(--main-dark) rounded-lg border border-(--border-light) dark:border-(--border-dark) p-6">
          <h2 class="text-lg font-semibold text-black dark:text-white mb-4">{{ t('Delivery Method') }}</h2>
          <div class="space-y-3">
            <label v-for="method in cartStore.deliveryMethods" :key="method.id"
              class="flex items-center gap-3 p-4 border rounded-lg cursor-pointer transition-colors" :class="cartStore.selectedDeliveryMethodId === method.id
                ? 'border-(--accent-blue-light) dark:border-(--accent-blue-dark) bg-blue-50 dark:bg-blue-900/20'
                : 'border-(--border-light) dark:border-(--border-dark) hover:border-gray-400'">
              <input type="radio" :value="method.id" v-model="selectedDeliveryMethod"
                class="w-4 h-4 text-(--accent-blue-light) dark:text-(--accent-blue-dark)" />
              <div class="flex-1">
                <div class="flex justify-between items-center">
                  <span class="text-black dark:text-white font-medium">{{ method.name }}</span>
                  <span class="text-(--accent-blue-light) dark:text-(--accent-blue-dark) font-medium">
                    {{ method.price > 0 ? `$${method.price.toFixed(2)}` : t('Free') }}
                  </span>
                </div>
                <p class="text-gray-500 dark:text-gray-400 text-sm">{{ method.description }}</p>
              </div>
            </label>
          </div>
        </div>
      </div>
    </div>
  </div>
  </component>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useCartStore } from '@/stores/cart'
import { useAddressStore } from '@/stores/address'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import Default from '@/layouts/default.vue'
const cartStore = useCartStore()
const addressStore = useAddressStore()
const { t } = useI18n()
const router = useRouter()

const selectedAddress = ref<number | null>(cartStore.selectedAddressId)
const selectedDeliveryMethod = ref<number | null>(cartStore.selectedDeliveryMethodId)
const addressSearchQuery = ref('')

watch(addressSearchQuery, (val) => {
  addressStore.setSearchQuery(val)
})

watch(selectedAddress, (newValue) => {
  cartStore.setSelectedAddress(newValue)
})

watch(selectedDeliveryMethod, (newValue) => {
  if (newValue) {
    cartStore.setDeliveryMethod(newValue)
  }
})

const canPlaceOrder = computed(() => {
  return cartStore.items.length > 0 &&
    cartStore.selectedAddressId !== null &&
    cartStore.selectedDeliveryMethodId !== null
})
function removeItem(itemId: number) {
  cartStore.removeItem(itemId)
}

function placeOrder() {
  if (canPlaceOrder.value) {
    console.log('Placing order...')
    alert(t('Order placed successfully!'))
    cartStore.clearCart()
    router.push({ name: 'home' })
  }
}

function cancelOrder() {
  router.back()
}
</script>
