<script lang="ts" setup>
import { Link } from '@inertiajs/vue3'
import { ref, computed } from 'vue'
import AccountLayout from '@/Layouts/AccountLayout.vue'
import type { Plan } from '@/types'

interface Props {
  plansByType: Record<string, Plan[]>
}

defineOptions({ layout: AccountLayout })

const props = defineProps<Props>()

// Active service type tab
const serviceTypes = computed(() => Object.keys(props.plansByType))
const activeTab = ref<string>(serviceTypes.value[0] || 'vps')

const serviceTypeMeta: Record<string, { label: string; icon: string; description: string }> = {
  vps: { label: 'VPS Servers', icon: 'tabler-server', description: 'High-performance NVMe virtual private servers' },
  dedicated: { label: 'Dedicated Servers', icon: 'tabler-server-cog', description: 'Bare-metal servers with full hardware access' },
  hosting: { label: 'Web Hosting', icon: 'tabler-world', description: 'Managed web hosting with cPanel alternative' },
  mysql: { label: 'MySQL Hosting', icon: 'tabler-database', description: 'Managed MySQL database hosting' },
  game: { label: 'Game Servers', icon: 'tabler-device-gamepad-2', description: 'Game server hosting with instant setup' },
}

// Billing cycle toggle
const billingCycle = ref<'monthly' | 'quarterly' | 'semi_annual' | 'annual'>('monthly')

const cycles = [
  { value: 'monthly' as const, label: 'Monthly', months: 1, discount: 0 },
  { value: 'quarterly' as const, label: 'Quarterly', months: 3, discount: 0.05 },
  { value: 'semi_annual' as const, label: 'Semi-Annual', months: 6, discount: 0.10 },
  { value: 'annual' as const, label: 'Annual', months: 12, discount: 0.15 },
]

const activeCycle = computed(() => cycles.find(c => c.value === billingCycle.value) || cycles[0])

function cyclePrice(basePrice: string): number {
  const monthly = parseFloat(basePrice)
  return monthly * (1 - activeCycle.value.discount) * activeCycle.value.months
}

function effectiveMonthly(basePrice: string): number {
  const monthly = parseFloat(basePrice)
  return monthly * (1 - activeCycle.value.discount)
}

// Popular plan slugs
const popularSlugs = new Set(['vps-mini', 'hosting-medium', 'mysql-silver'])
const bestValueSlugs = new Set(['vps-standard'])

function isPlanPopular(plan: Plan): boolean {
  return popularSlugs.has(plan.slug)
}

function isPlanBestValue(plan: Plan): boolean {
  return bestValueSlugs.has(plan.slug)
}

// Feature display config per service type
interface FeatureDisplay {
  key: string
  label: string
  icon: string
}

const featureConfig: Record<string, FeatureDisplay[]> = {
  vps: [
    { key: 'cpu', label: 'CPU', icon: 'tabler-cpu' },
    { key: 'ram', label: 'RAM', icon: 'tabler-brand-stackoverflow' },
    { key: 'storage', label: 'Storage', icon: 'tabler-database' },
    { key: 'bandwidth', label: 'Bandwidth', icon: 'tabler-transfer' },
    { key: 'ipv4', label: 'IPv4', icon: 'tabler-network' },
    { key: 'os', label: 'OS', icon: 'tabler-brand-ubuntu' },
  ],
  dedicated: [
    { key: 'cpu', label: 'CPU', icon: 'tabler-cpu' },
    { key: 'cores', label: 'Cores', icon: 'tabler-cpu-2' },
    { key: 'ram', label: 'RAM', icon: 'tabler-brand-stackoverflow' },
    { key: 'storage_bays', label: 'Storage Bays', icon: 'tabler-database' },
    { key: 'bandwidth', label: 'Bandwidth', icon: 'tabler-transfer' },
    { key: 'ipv4', label: 'IPv4', icon: 'tabler-network' },
  ],
  hosting: [
    { key: 'storage', label: 'Storage', icon: 'tabler-database' },
    { key: 'domains', label: 'Domains', icon: 'tabler-world' },
    { key: 'email', label: 'Email', icon: 'tabler-mail' },
    { key: 'databases', label: 'Databases', icon: 'tabler-database' },
    { key: 'bandwidth', label: 'Bandwidth', icon: 'tabler-transfer' },
    { key: 'ssl', label: 'SSL', icon: 'tabler-lock' },
  ],
  mysql: [
    { key: 'storage', label: 'Storage', icon: 'tabler-database' },
    { key: 'backups', label: 'Backups', icon: 'tabler-cloud-upload' },
    { key: 'ssl', label: 'Security', icon: 'tabler-lock' },
  ],
  game: [
    { key: 'cpu', label: 'CPU', icon: 'tabler-cpu' },
    { key: 'ram', label: 'RAM', icon: 'tabler-brand-stackoverflow' },
    { key: 'storage', label: 'Storage', icon: 'tabler-database' },
    { key: 'bandwidth', label: 'Bandwidth', icon: 'tabler-transfer' },
  ],
}

function getFeaturesForType(type: string): FeatureDisplay[] {
  return featureConfig[type] || featureConfig.vps
}

function isOutOfStock(plan: Plan): boolean {
  return plan.stock_quantity !== null && plan.stock_quantity <= 0
}

function stockLabel(plan: Plan): string | null {
  if (plan.stock_quantity === null) return null
  if (plan.stock_quantity <= 0) return 'Out of Stock'
  if (plan.stock_quantity <= 3) return `${plan.stock_quantity} left`
  return null
}
</script>

<template>
  <div>
    <!-- Header -->
    <div class="text-center mb-8">
      <div class="text-h4 font-weight-bold mb-2">
        Plans & Pricing
      </div>
      <div class="text-body-1 text-medium-emphasis mx-auto" style="max-width: 560px;">
        Choose the perfect plan for your needs. All plans include responsive support and a 99.9% uptime SLA.
      </div>
    </div>

    <!-- Billing Cycle Toggle -->
    <div class="d-flex justify-center mb-8">
      <div class="cycle-toggle-wrapper">
        <div
          v-for="cycle in cycles"
          :key="cycle.value"
          class="cycle-option"
          :class="{ 'cycle-option--active': billingCycle === cycle.value }"
          @click="billingCycle = cycle.value"
        >
          <span class="cycle-option__label">{{ cycle.label }}</span>
          <span v-if="cycle.discount > 0" class="cycle-option__discount">
            Save {{ (cycle.discount * 100).toFixed(0) }}%
          </span>
        </div>
      </div>
    </div>

    <!-- Service Type Tabs -->
    <VTabs
      v-model="activeTab"
      color="primary"
      class="mb-6"
      show-arrows
    >
      <VTab
        v-for="type in serviceTypes"
        :key="type"
        :value="type"
      >
        <VIcon :icon="serviceTypeMeta[type]?.icon || 'tabler-server'" size="20" start />
        {{ serviceTypeMeta[type]?.label || type }}
      </VTab>
    </VTabs>

    <!-- Plans Grid -->
    <VWindow v-model="activeTab">
      <VWindowItem
        v-for="(plans, type) in plansByType"
        :key="type"
        :value="type"
      >
        <!-- Type description -->
        <div v-if="serviceTypeMeta[type as string]?.description" class="text-body-2 text-medium-emphasis mb-5">
          {{ serviceTypeMeta[type as string].description }}
        </div>

        <VRow>
          <VCol
            v-for="plan in plans"
            :key="plan.id"
            cols="12"
            sm="6"
            :lg="plans.length <= 3 ? 4 : 3"
          >
            <VCard
              class="plan-card d-flex flex-column h-100"
              :class="{
                'plan-card--popular': isPlanPopular(plan),
                'plan-card--best-value': isPlanBestValue(plan),
                'plan-card--out-of-stock': isOutOfStock(plan),
              }"
              :elevation="isPlanPopular(plan) || isPlanBestValue(plan) ? 4 : 1"
            >
              <!-- Badge -->
              <div v-if="isPlanPopular(plan)" class="plan-badge plan-badge--popular">
                Most Popular
              </div>
              <div v-else-if="isPlanBestValue(plan)" class="plan-badge plan-badge--best-value">
                Best Value
              </div>

              <!-- Stock indicator -->
              <div v-if="stockLabel(plan)" class="stock-indicator" :class="{ 'stock-indicator--out': isOutOfStock(plan) }">
                <VIcon :icon="isOutOfStock(plan) ? 'tabler-alert-circle' : 'tabler-flame'" size="14" class="me-1" />
                {{ stockLabel(plan) }}
              </div>

              <VCardText class="pa-5 pb-0">
                <!-- Plan name -->
                <div class="text-h6 font-weight-bold mb-1">
                  {{ plan.name }}
                </div>

                <div v-if="plan.description" class="text-caption text-medium-emphasis mb-4" style="min-height: 32px;">
                  {{ plan.description }}
                </div>

                <!-- Price -->
                <div class="price-block mb-4">
                  <div class="d-flex align-end gap-1">
                    <span class="text-h4 font-weight-bold price-amount">
                      ${{ effectiveMonthly(plan.price).toFixed(2) }}
                    </span>
                    <span class="text-body-2 text-medium-emphasis pb-1">/mo</span>
                  </div>
                  <div v-if="billingCycle !== 'monthly'" class="text-caption text-medium-emphasis mt-1">
                    ${{ cyclePrice(plan.price).toFixed(2) }} billed {{ activeCycle.label.toLowerCase() }}
                  </div>
                  <div v-if="activeCycle.discount > 0" class="text-caption text-success mt-1">
                    Save ${{ (parseFloat(plan.price) * activeCycle.discount * activeCycle.months).toFixed(2) }}
                  </div>
                </div>

                <VDivider class="mb-4" />

                <!-- Features -->
                <div class="features-list">
                  <div
                    v-for="feat in getFeaturesForType(type as string)"
                    :key="feat.key"
                    class="feature-row"
                  >
                    <VIcon :icon="feat.icon" size="18" color="primary" class="feature-icon" />
                    <span class="text-body-2">
                      <span class="text-medium-emphasis">{{ feat.label }}:</span>
                      <span class="font-weight-medium ms-1">{{ plan.features?.[feat.key] || '---' }}</span>
                    </span>
                  </div>
                </div>
              </VCardText>

              <VSpacer />

              <!-- CTA -->
              <VCardActions class="pa-5 pt-4">
                <span
                  v-if="isOutOfStock(plan)"
                  class="text-body-2 font-weight-medium text-error w-100 text-center"
                >
                  Out of Stock
                </span>
                <Link
                  v-else
                  :href="`/checkout/${plan.id}`"
                  class="text-decoration-none w-100"
                >
                  <VBtn
                    block
                    :color="isPlanPopular(plan) || isPlanBestValue(plan) ? 'primary' : undefined"
                    :variant="isPlanPopular(plan) || isPlanBestValue(plan) ? 'flat' : 'outlined'"
                    size="large"
                    class="order-btn"
                  >
                    <VIcon icon="tabler-shopping-cart" start size="18" />
                    Order Now
                  </VBtn>
                </Link>
              </VCardActions>
            </VCard>
          </VCol>
        </VRow>
      </VWindowItem>
    </VWindow>

    <!-- Empty state -->
    <div v-if="!plansByType || Object.keys(plansByType).length === 0" class="text-center py-16">
      <VIcon icon="tabler-package-off" size="64" color="disabled" class="mb-4" />
      <div class="text-h6 text-medium-emphasis mb-2">
        No plans available
      </div>
      <div class="text-body-2 text-medium-emphasis">
        Plans are being configured. Please check back soon.
      </div>
    </div>
  </div>
</template>

<style scoped>
/* Cycle toggle */
.cycle-toggle-wrapper {
  display: inline-flex;
  gap: 4px;
  padding: 4px;
  border-radius: 14px;
  background: rgba(var(--v-theme-on-surface), 0.06);
  border: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
}

.cycle-option {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
  padding: 10px 24px;
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
  user-select: none;
  position: relative;
}

.cycle-option:hover:not(.cycle-option--active) {
  background: rgba(var(--v-theme-on-surface), 0.04);
}

.cycle-option--active {
  background: rgb(var(--v-theme-primary));
  box-shadow: 0 4px 14px rgba(115, 103, 240, 0.4);
}

.cycle-option__label {
  font-size: 0.875rem;
  font-weight: 600;
  color: rgba(var(--v-theme-on-surface), 0.7);
  white-space: nowrap;
  line-height: 1.2;
}

.cycle-option--active .cycle-option__label {
  color: #fff;
}

.cycle-option__discount {
  font-size: 0.65rem;
  font-weight: 700;
  letter-spacing: 0.3px;
  color: rgb(var(--v-theme-success));
  line-height: 1;
}

.cycle-option--active .cycle-option__discount {
  color: rgba(255, 255, 255, 0.85);
}

@media (max-width: 600px) {
  .cycle-toggle-wrapper {
    flex-wrap: wrap;
    justify-content: center;
  }

  .cycle-option {
    padding: 8px 16px;
  }
}

/* Plan cards */
.plan-card {
  position: relative;
  border-radius: 16px;
  border: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: visible;
}

.plan-card:hover {
  transform: translateY(-6px);
  box-shadow: 0 16px 40px rgba(0, 0, 0, 0.12) !important;
}

.plan-card--popular {
  border-color: rgb(var(--v-theme-primary));
  border-width: 2px;
}

.plan-card--popular:hover {
  box-shadow: 0 16px 40px rgba(115, 103, 240, 0.2) !important;
}

.plan-card--best-value {
  border-color: rgb(var(--v-theme-success));
  border-width: 2px;
}

.plan-card--best-value:hover {
  box-shadow: 0 16px 40px rgba(40, 199, 111, 0.15) !important;
}

.plan-card--out-of-stock {
  opacity: 0.6;
}

.plan-card--out-of-stock:hover {
  transform: none;
}

/* Badges */
.plan-badge {
  position: absolute;
  top: -12px;
  left: 50%;
  transform: translateX(-50%);
  padding: 4px 16px;
  border-radius: 20px;
  font-size: 0.7rem;
  font-weight: 700;
  letter-spacing: 0.5px;
  text-transform: uppercase;
  white-space: nowrap;
  z-index: 1;
}

.plan-badge--popular {
  background: rgb(var(--v-theme-primary));
  color: white;
  box-shadow: 0 4px 12px rgba(115, 103, 240, 0.4);
}

.plan-badge--best-value {
  background: rgb(var(--v-theme-success));
  color: white;
  box-shadow: 0 4px 12px rgba(40, 199, 111, 0.4);
}

/* Stock indicator */
.stock-indicator {
  position: absolute;
  top: 12px;
  right: 12px;
  padding: 2px 8px;
  border-radius: 6px;
  font-size: 0.7rem;
  font-weight: 600;
  background: rgba(var(--v-theme-warning), 0.15);
  color: rgb(var(--v-theme-warning));
  display: flex;
  align-items: center;
}

.stock-indicator--out {
  background: rgba(var(--v-theme-error), 0.15);
  color: rgb(var(--v-theme-error));
}

/* Price */
.price-amount {
  color: rgb(var(--v-theme-primary));
  line-height: 1;
}

/* Features */
.features-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.feature-row {
  display: flex;
  align-items: center;
  gap: 10px;
}

.feature-icon {
  flex-shrink: 0;
}

/* Order button */
.order-btn {
  font-weight: 600;
  letter-spacing: 0.3px;
  transition: all 0.2s ease;
}

.order-btn:hover {
  transform: translateY(-1px);
}
</style>
