<script lang="ts" setup>
import { Link, useForm, router, usePage } from '@inertiajs/vue3'
import { computed, ref } from 'vue'
import AccountLayout from '@/Layouts/AccountLayout.vue'
import { crossDomainUrl } from '@/utils/resolvers'

defineOptions({ layout: AccountLayout })

interface CartPlan {
  id: number
  name: string
  service_type: string
  description: string | null
  features: Record<string, string> | null
}

interface CartItemData {
  id: number
  plan_id: number
  billing_cycle: string
  quantity: number
  config_selections: Record<string, unknown> | null
  coupon_code: string | null
  unit_price: string
  line_total: string
  plan: CartPlan | null
}

interface Props {
  items: CartItemData[]
  total: string
  itemCount: number
}

interface PageProps {
  domains: { marketing: string; account: string; admin: string }
}

const props = defineProps<Props>()
const page = usePage()
const pageProps = computed(() => page.props as unknown as PageProps)
const accountUrl = computed(() => crossDomainUrl(pageProps.value.domains?.account))

const removeLoading = ref<number | null>(null)

const billingCycleLabels: Record<string, string> = {
  monthly: 'Monthly',
  quarterly: 'Quarterly',
  semi_annual: 'Semi-Annual',
  annual: 'Annual',
}

function serviceTypeIcon(type: string): string {
  const icons: Record<string, string> = {
    vps: 'tabler-cloud',
    dedicated: 'tabler-server',
    hosting: 'tabler-world',
    game: 'tabler-device-gamepad-2',
    mysql: 'tabler-database',
    backups: 'tabler-cloud-upload',
  }
  return icons[type] ?? 'tabler-package'
}

function updateQuantity(item: CartItemData, qty: number): void {
  if (qty < 1 || qty > 10) return
  router.put(`/cart/${item.id}`, { quantity: qty }, { preserveScroll: true })
}

function removeItem(item: CartItemData): void {
  removeLoading.value = item.id
  router.delete(`/cart/${item.id}`, {
    preserveScroll: true,
    onFinish: () => { removeLoading.value = null },
  })
}

function proceedToCheckout(): void {
  // If there's exactly one item, redirect to single-plan checkout
  if (props.items.length === 1) {
    const item = props.items[0]
    router.visit(`${accountUrl.value}/checkout/${item.plan_id}?cycle=${item.billing_cycle}`)
  } else {
    // For multi-item, go to the first item's checkout (cart checkout is future)
    const item = props.items[0]
    router.visit(`${accountUrl.value}/checkout/${item.plan_id}?cycle=${item.billing_cycle}`)
  }
}
</script>

<template>
  <div>
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="text-h4 font-weight-bold">
          Shopping Cart
        </div>
        <div class="text-body-2 text-medium-emphasis">
          {{ props.itemCount }} {{ props.itemCount === 1 ? 'item' : 'items' }} in your cart
        </div>
      </div>
    </div>

    <!-- Empty Cart -->
    <VCard v-if="props.items.length === 0" class="text-center py-16">
      <VCardText>
        <VIcon icon="tabler-shopping-cart-off" size="64" color="disabled" class="mb-4" />
        <div class="text-h6 mb-2">
          Your cart is empty
        </div>
        <div class="text-body-2 text-medium-emphasis mb-6">
          Browse our plans and add items to get started.
        </div>
        <Link :href="crossDomainUrl(pageProps.domains?.marketing) + '/pricing'">
          <VBtn color="primary" prepend-icon="tabler-package">
            Browse Plans
          </VBtn>
        </Link>
      </VCardText>
    </VCard>

    <!-- Cart Items -->
    <template v-else>
      <VRow>
        <VCol cols="12" lg="8">
          <VCard v-for="item in props.items" :key="item.id" class="mb-4">
            <VCardText>
              <div class="d-flex align-start gap-4">
                <!-- Plan Icon -->
                <VAvatar
                  v-if="item.plan"
                  color="primary"
                  variant="tonal"
                  size="48"
                  rounded
                >
                  <VIcon :icon="serviceTypeIcon(item.plan.service_type)" size="24" />
                </VAvatar>

                <!-- Plan Details -->
                <div class="flex-grow-1">
                  <div class="d-flex align-center justify-space-between mb-1">
                    <div>
                      <span class="text-body-1 font-weight-medium">
                        {{ item.plan?.name ?? 'Unknown Plan' }}
                      </span>
                      <VChip
                        size="x-small"
                        color="info"
                        variant="tonal"
                        class="ms-2 text-capitalize"
                      >
                        {{ item.plan?.service_type ?? 'unknown' }}
                      </VChip>
                    </div>
                    <span class="text-body-1 font-weight-bold">
                      ${{ item.line_total }}
                    </span>
                  </div>

                  <div class="text-body-2 text-medium-emphasis mb-3">
                    {{ billingCycleLabels[item.billing_cycle] ?? item.billing_cycle }} billing
                    &middot; ${{ item.unit_price }}/{{ item.billing_cycle }}
                  </div>

                  <!-- Quantity & Actions -->
                  <div class="d-flex align-center gap-3">
                    <div class="d-flex align-center gap-1">
                      <VBtn
                        icon="tabler-minus"
                        variant="text"
                        size="x-small"
                        :disabled="item.quantity <= 1"
                        @click="updateQuantity(item, item.quantity - 1)"
                      />
                      <span class="text-body-2 font-weight-medium" style="min-width: 24px; text-align: center;">
                        {{ item.quantity }}
                      </span>
                      <VBtn
                        icon="tabler-plus"
                        variant="text"
                        size="x-small"
                        :disabled="item.quantity >= 10"
                        @click="updateQuantity(item, item.quantity + 1)"
                      />
                    </div>

                    <VSpacer />

                    <VBtn
                      variant="text"
                      size="small"
                      color="error"
                      :loading="removeLoading === item.id"
                      @click="removeItem(item)"
                    >
                      <VIcon icon="tabler-trash" start size="16" />
                      Remove
                    </VBtn>
                  </div>
                </div>
              </div>
            </VCardText>
          </VCard>
        </VCol>

        <!-- Order Summary -->
        <VCol cols="12" lg="4">
          <VCard>
            <VCardTitle>
              Order Summary
            </VCardTitle>
            <VCardText>
              <div v-for="item in props.items" :key="item.id" class="d-flex justify-space-between mb-2">
                <span class="text-body-2 text-medium-emphasis text-truncate" style="max-width: 200px;">
                  {{ item.plan?.name ?? 'Unknown' }} x{{ item.quantity }}
                </span>
                <span class="text-body-2 font-weight-medium">${{ item.line_total }}</span>
              </div>

              <VDivider class="my-3" />

              <div class="d-flex justify-space-between align-center">
                <span class="text-body-1 font-weight-bold">Total</span>
                <span class="text-h5 font-weight-bold text-primary">${{ props.total }}</span>
              </div>

              <VBtn
                color="primary"
                block
                size="large"
                class="mt-4"
                prepend-icon="tabler-credit-card"
                @click="proceedToCheckout"
              >
                Proceed to Checkout
              </VBtn>

              <Link :href="crossDomainUrl(pageProps.domains?.marketing) + '/pricing'" class="text-decoration-none">
                <VBtn
                  variant="text"
                  block
                  size="small"
                  class="mt-2"
                >
                  Continue Shopping
                </VBtn>
              </Link>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>
    </template>
  </div>
</template>
