<script lang="ts" setup>
import { ref, computed, watch } from 'vue'
import type { PlanConfigGroup, PlanConfigOption } from '@/types'

interface Props {
  configGroup: PlanConfigGroup
  billingCycle: string
  accountUrl: string
}

const props = defineProps<Props>()

const emit = defineEmits<{
  deploy: [payload: { serviceType: string; selections: Record<number, number>; total: number }]
}>()

// Track slider/quantity values keyed by option_id
const values = ref<Record<number, number>>({})

// Initialize default values
function initValues(): void {
  const vals: Record<number, number> = {}
  for (const option of props.configGroup.options) {
    if (option.type === 'slider' || option.type === 'quantity') {
      vals[option.id] = option.min_qty ?? 0
    }
  }
  values.value = vals
}
initValues()

// Cycle-aware pricing
const cycleKey = computed<string>(() => `${props.billingCycle}_price`)

function getOptionPrice(option: PlanConfigOption): number {
  const key = cycleKey.value as keyof PlanConfigOption
  return Number(option[key] ?? option.monthly_price ?? 0)
}

function getOptionHourlyPrice(option: PlanConfigOption): number {
  return Number(option.hourly_price ?? 0)
}

// Calculate totals
const monthlyTotal = computed<number>(() => {
  let total = 0
  for (const option of props.configGroup.options) {
    if (option.type === 'slider' || option.type === 'quantity') {
      const qty = values.value[option.id] ?? 0
      total += Number(option.monthly_price ?? 0) * qty
    }
  }
  return total
})

const cycleTotal = computed<number>(() => {
  let total = 0
  for (const option of props.configGroup.options) {
    if (option.type === 'slider' || option.type === 'quantity') {
      const qty = values.value[option.id] ?? 0
      total += getOptionPrice(option) * qty
    }
  }
  return total
})

const hourlyTotal = computed<number>(() => {
  let total = 0
  for (const option of props.configGroup.options) {
    if (option.type === 'slider' || option.type === 'quantity') {
      const qty = values.value[option.id] ?? 0
      total += getOptionHourlyPrice(option) * qty
    }
  }
  return total
})

// Line items for summary
const lineItems = computed<Array<{ name: string; qty: number; unitLabel: string; price: number; hourly: number }>>(() => {
  return props.configGroup.options
    .filter(opt => (opt.type === 'slider' || opt.type === 'quantity') && (values.value[opt.id] ?? 0) > 0)
    .map(opt => ({
      name: opt.name,
      qty: values.value[opt.id] ?? 0,
      unitLabel: opt.unit_label ?? '',
      price: getOptionPrice(opt) * (values.value[opt.id] ?? 0),
      hourly: getOptionHourlyPrice(opt) * (values.value[opt.id] ?? 0),
    }))
})

const serviceType = computed<string>(() => props.configGroup.service_type ?? 'vps')

const cycleLabel = computed<string>(() => {
  switch (props.billingCycle) {
    case 'quarterly': return 'quarter'
    case 'semi_annual': return '6 months'
    case 'annual': return 'year'
    default: return 'month'
  }
})

function handleDeploy(): void {
  emit('deploy', {
    serviceType: serviceType.value,
    selections: { ...values.value },
    total: cycleTotal.value,
  })
}

const deployUrl = computed<string>(() => {
  return `${props.accountUrl}/checkout/custom/${serviceType.value}?cycle=${props.billingCycle}`
})
</script>

<template>
  <VRow>
    <!-- Sliders Column -->
    <VCol
      cols="12"
      md="7"
      lg="8"
    >
      <div
        v-for="option in configGroup.options.filter(o => o.type === 'slider' || o.type === 'quantity')"
        :key="option.id"
        class="byo-slider-row mb-6"
      >
        <div class="d-flex justify-space-between align-center mb-2">
          <div>
            <span class="text-body-1 font-weight-bold">{{ option.name }}</span>
            <span
              v-if="option.description"
              class="text-caption text-medium-emphasis ml-2"
            >{{ option.description }}</span>
          </div>
          <div class="d-flex align-center ga-2">
            <span class="text-h6 font-weight-bold text-primary">
              {{ values[option.id] ?? 0 }} {{ option.unit_label ?? '' }}
            </span>
            <VChip
              v-if="getOptionHourlyPrice(option) > 0"
              size="small"
              color="info"
              variant="tonal"
            >
              ${{ (getOptionHourlyPrice(option) * (values[option.id] ?? 0)).toFixed(4) }}/hr
            </VChip>
          </div>
        </div>

        <VSlider
          v-model="values[option.id]"
          :min="option.min_qty ?? 0"
          :max="option.max_qty ?? 100"
          :step="option.step ?? 1"
          color="primary"
          track-color="grey-lighten-2"
          thumb-label="always"
          class="byo-slider"
        >
          <template #thumb-label="{ modelValue }">
            {{ modelValue }}
          </template>
        </VSlider>

        <div class="d-flex justify-space-between text-caption text-medium-emphasis mt-n2">
          <span>{{ option.min_qty ?? 0 }} {{ option.unit_label ?? '' }}</span>
          <span
            v-if="getOptionPrice(option) > 0"
            class="text-primary font-weight-medium"
          >
            ${{ getOptionPrice(option).toFixed(2) }}/{{ option.unit_label ?? 'unit' }}
          </span>
          <span>{{ option.max_qty ?? 100 }} {{ option.unit_label ?? '' }}</span>
        </div>
      </div>
    </VCol>

    <!-- Price Summary Column (Sticky) -->
    <VCol
      cols="12"
      md="5"
      lg="4"
    >
      <div class="byo-summary-wrapper">
        <VCard
          elevation="3"
          class="byo-summary-card"
        >
          <VCardTitle class="text-h6 pb-2">
            <VIcon
              icon="tabler-receipt"
              size="22"
              class="me-2"
            />
            Price Summary
          </VCardTitle>

          <VCardText>
            <!-- Hourly Rate -->
            <div
              v-if="hourlyTotal > 0"
              class="d-flex justify-space-between align-center mb-3"
            >
              <span class="text-body-2 text-medium-emphasis">Hourly Rate</span>
              <span class="text-h6 font-weight-bold text-primary">${{ hourlyTotal.toFixed(4) }}/hr</span>
            </div>

            <!-- Monthly Cap -->
            <div class="d-flex justify-space-between align-center mb-4">
              <span class="text-body-2 text-medium-emphasis">Monthly Cap</span>
              <span class="text-h5 font-weight-bold text-primary">${{ monthlyTotal.toFixed(2) }}/mo</span>
            </div>

            <VDivider class="mb-4" />

            <!-- Line Items -->
            <div
              v-for="item in lineItems"
              :key="item.name"
              class="d-flex justify-space-between text-body-2 mb-2"
            >
              <span class="text-medium-emphasis">
                {{ item.qty }} {{ item.unitLabel }} {{ item.name }}
              </span>
              <span class="font-weight-medium">${{ item.price.toFixed(2) }}</span>
            </div>

            <div
              v-if="lineItems.length === 0"
              class="text-center text-body-2 text-medium-emphasis py-4"
            >
              Adjust sliders to configure your server
            </div>

            <VDivider
              v-if="lineItems.length > 0"
              class="my-3"
            />

            <!-- Cycle Total -->
            <div
              v-if="lineItems.length > 0"
              class="d-flex justify-space-between align-center mb-4"
            >
              <span class="text-body-1 font-weight-bold">Total per {{ cycleLabel }}</span>
              <span class="text-h5 font-weight-bold text-primary">${{ cycleTotal.toFixed(2) }}</span>
            </div>

            <!-- Deploy Button -->
            <a
              :href="deployUrl"
              class="text-decoration-none d-block"
            >
              <VBtn
                block
                size="large"
                color="primary"
                :disabled="cycleTotal === 0"
                @click="handleDeploy"
              >
                <VIcon
                  icon="tabler-rocket"
                  start
                  size="20"
                />
                Deploy Now
              </VBtn>
            </a>

            <div class="text-center text-caption text-medium-emphasis mt-3">
              <VIcon
                icon="tabler-clock"
                size="14"
              />
              Deployed in under 60 seconds
            </div>
          </VCardText>
        </VCard>
      </div>
    </VCol>
  </VRow>
</template>

<style scoped>
.byo-slider-row {
  padding: 1rem 1.25rem;
  border: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
  border-radius: 12px;
  background: rgba(var(--v-theme-surface), 1);
  transition: border-color 0.2s ease;
}

.byo-slider-row:hover {
  border-color: rgba(var(--v-theme-primary), 0.3);
}

.byo-summary-wrapper {
  position: sticky;
  top: 100px;
}

.byo-summary-card {
  border-top: 3px solid rgb(var(--v-theme-primary));
  background: linear-gradient(135deg, rgba(var(--v-theme-surface), 1) 0%, rgba(var(--v-theme-surface), 0.95) 100%);
}

.byo-slider :deep(.v-slider-thumb__label) {
  font-weight: 700;
}

@media (max-width: 960px) {
  .byo-summary-wrapper {
    position: static !important;
  }
}
</style>
