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

type OptionFormData = Omit<PlanConfigOption, 'id' | 'group_id' | 'sort_order'> & {
  id?: number
  group_id?: number
  sort_order?: number
}

interface Props {
  modelValue: OptionFormData[]
  mode: 'preset' | 'build_your_own'
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'update:modelValue': [value: OptionFormData[]]
}>()

const options = computed({
  get: () => props.modelValue,
  set: (val: OptionFormData[]) => emit('update:modelValue', val),
})

const optionTypeItems = [
  { title: 'Dropdown', value: 'dropdown' },
  { title: 'Radio', value: 'radio' },
  { title: 'Quantity', value: 'quantity' },
  { title: 'Checkbox', value: 'checkbox' },
  { title: 'Text', value: 'text' },
  { title: 'Slider', value: 'slider' },
]

const pricingCycles: { label: string; key: string }[] = [
  { label: 'Hourly', key: 'hourly_price' },
  { label: 'Monthly', key: 'monthly_price' },
  { label: 'Quarterly', key: 'quarterly_price' },
  { label: 'Semi-Annual', key: 'semi_annual_price' },
  { label: 'Annual', key: 'annual_price' },
]

function isQuantityOrSlider(type: string): boolean {
  return ['quantity', 'slider'].includes(type)
}

function hasValues(type: string): boolean {
  return ['dropdown', 'radio', 'checkbox'].includes(type)
}

function addOption(): void {
  const updated = [...options.value]
  updated.push({
    name: '',
    description: null,
    type: 'dropdown',
    provisioning_key: null,
    required: false,
    is_active: true,
    min_qty: null,
    max_qty: null,
    step: null,
    unit_label: null,
    hourly_price: null,
    monthly_price: null,
    quarterly_price: null,
    semi_annual_price: null,
    annual_price: null,
    values: [],
  })
  options.value = updated
}

function removeOption(index: number): void {
  const updated = [...options.value]
  updated.splice(index, 1)
  options.value = updated
}

function addValue(optionIndex: number): void {
  const updated = [...options.value]
  const option = { ...updated[optionIndex] }
  option.values = [...(option.values || [])]
  option.values.push({
    id: 0,
    option_id: 0,
    label: '',
    value: null,
    hourly_price: 0,
    monthly_price: 0,
    quarterly_price: 0,
    semi_annual_price: 0,
    annual_price: 0,
    is_default: false,
    sort_order: 0,
  })
  updated[optionIndex] = option
  options.value = updated
}

function removeValue(optionIndex: number, valueIndex: number): void {
  const updated = [...options.value]
  const option = { ...updated[optionIndex] }
  option.values = [...(option.values || [])]
  option.values.splice(valueIndex, 1)
  updated[optionIndex] = option
  options.value = updated
}

// Auto-compute multi-cycle prices from monthly base
function computeFromMonthly(monthly: number): { quarterly: number; semi_annual: number; annual: number } {
  return {
    quarterly: Math.round(monthly * 3 * 0.95 * 100) / 100,
    semi_annual: Math.round(monthly * 6 * 0.90 * 100) / 100,
    annual: Math.round(monthly * 12 * 0.85 * 100) / 100,
  }
}

function autoComputeOptionPricing(optionIndex: number): void {
  const updated = [...options.value]
  const option = { ...updated[optionIndex] }
  const monthly = Number(option.monthly_price) || 0
  if (monthly > 0) {
    const computed = computeFromMonthly(monthly)
    option.quarterly_price = computed.quarterly
    option.semi_annual_price = computed.semi_annual
    option.annual_price = computed.annual
  }
  updated[optionIndex] = option
  options.value = updated
}

function autoComputeValuePricing(optionIndex: number, valueIndex: number): void {
  const updated = [...options.value]
  const option = { ...updated[optionIndex] }
  option.values = [...(option.values || [])]
  const val = { ...option.values[valueIndex] }
  const monthly = Number(val.monthly_price) || 0
  if (monthly > 0) {
    const computed = computeFromMonthly(monthly)
    val.quarterly_price = computed.quarterly
    val.semi_annual_price = computed.semi_annual
    val.annual_price = computed.annual
  }
  option.values[valueIndex] = val
  updated[optionIndex] = option
  options.value = updated
}
</script>

<template>
  <div>
    <VExpansionPanels
      v-if="options.length > 0"
      variant="accordion"
      class="mb-4"
    >
      <VExpansionPanel
        v-for="(option, optIndex) in options"
        :key="optIndex"
      >
        <VExpansionPanelTitle>
          <div class="d-flex align-center justify-space-between w-100 pe-4">
            <div class="d-flex align-center gap-2">
              <VIcon icon="tabler-grip-vertical" size="18" color="disabled" />
              <span class="font-weight-medium">
                {{ option.name || `Option ${optIndex + 1}` }}
              </span>
              <VChip size="x-small" variant="tonal" color="info">
                {{ option.type }}
              </VChip>
              <VChip v-if="option.required" size="x-small" variant="tonal" color="warning">
                Required
              </VChip>
              <VChip v-if="!option.is_active" size="x-small" variant="tonal" color="error">
                Inactive
              </VChip>
            </div>
            <VBtn
              icon="tabler-trash"
              variant="text"
              color="error"
              size="x-small"
              @click.stop="removeOption(optIndex)"
            />
          </div>
        </VExpansionPanelTitle>
        <VExpansionPanelText>
          <VRow>
            <VCol cols="12" md="4">
              <VTextField
                v-model="option.name"
                label="Option Name"
                placeholder="e.g. RAM, CPU Cores"
                density="compact"
              />
            </VCol>
            <VCol cols="12" md="4">
              <VSelect
                v-model="option.type"
                label="Type"
                :items="optionTypeItems"
                density="compact"
              />
            </VCol>
            <VCol cols="12" md="4">
              <VTextField
                v-model="option.provisioning_key"
                label="Provisioning Key"
                placeholder="e.g. ram, cpu_cores"
                density="compact"
                hint="Used by provisioning API"
                persistent-hint
              />
            </VCol>
            <VCol cols="12">
              <VTextField
                v-model="option.description"
                label="Description"
                placeholder="Optional description for this option"
                density="compact"
              />
            </VCol>
            <VCol cols="6" md="3">
              <VSwitch
                v-model="option.required"
                label="Required"
                density="compact"
                hide-details
              />
            </VCol>
            <VCol cols="6" md="3">
              <VSwitch
                v-model="option.is_active"
                label="Active"
                density="compact"
                hide-details
              />
            </VCol>
          </VRow>

          <!-- Quantity/Slider fields -->
          <template v-if="isQuantityOrSlider(option.type)">
            <VDivider class="my-4" />
            <div class="text-subtitle-2 font-weight-medium mb-3">
              Range & Unit
            </div>
            <VRow>
              <VCol cols="6" md="3">
                <VTextField
                  v-model.number="option.min_qty"
                  label="Min"
                  type="number"
                  min="0"
                  density="compact"
                />
              </VCol>
              <VCol cols="6" md="3">
                <VTextField
                  v-model.number="option.max_qty"
                  label="Max"
                  type="number"
                  min="0"
                  density="compact"
                />
              </VCol>
              <VCol cols="6" md="3">
                <VTextField
                  v-model.number="option.step"
                  label="Step"
                  type="number"
                  min="1"
                  density="compact"
                />
              </VCol>
              <VCol cols="6" md="3">
                <VTextField
                  v-model="option.unit_label"
                  label="Unit Label"
                  placeholder="e.g. GB, cores"
                  density="compact"
                />
              </VCol>
            </VRow>

            <div class="d-flex align-center justify-space-between mt-4 mb-3">
              <span class="text-subtitle-2 font-weight-medium">Per-Unit Pricing</span>
              <VBtn
                variant="tonal"
                color="info"
                size="x-small"
                prepend-icon="tabler-calculator"
                :disabled="!option.monthly_price || Number(option.monthly_price) <= 0"
                @click="autoComputeOptionPricing(optIndex)"
              >
                Auto-compute from monthly
              </VBtn>
            </div>
            <VRow>
              <VCol
                v-for="cycle in pricingCycles"
                :key="cycle.key"
                cols="6"
                md="2"
              >
                <VTextField
                  v-model.number="(option as Record<string, unknown>)[cycle.key]"
                  :label="cycle.label"
                  type="number"
                  step="0.01"
                  min="0"
                  density="compact"
                  prefix="$"
                />
              </VCol>
            </VRow>
          </template>

          <!-- Values for dropdown/radio/checkbox -->
          <template v-if="hasValues(option.type)">
            <VDivider class="my-4" />
            <div class="d-flex align-center justify-space-between mb-3">
              <span class="text-subtitle-2 font-weight-medium">Values</span>
              <VBtn
                variant="tonal"
                color="primary"
                prepend-icon="tabler-plus"
                size="x-small"
                @click="addValue(optIndex)"
              >
                Add Value
              </VBtn>
            </div>

            <div v-if="!option.values || option.values.length === 0" class="text-center py-4">
              <span class="text-medium-emphasis text-body-2">No values yet. Add at least one.</span>
            </div>

            <VCard
              v-for="(val, valIndex) in option.values"
              :key="valIndex"
              variant="outlined"
              class="mb-3 pa-3"
            >
              <VRow align="center">
                <VCol cols="12" md="3">
                  <VTextField
                    v-model="val.label"
                    label="Label"
                    placeholder="e.g. 64 GB"
                    density="compact"
                    hide-details
                  />
                </VCol>
                <VCol cols="12" md="3">
                  <VTextField
                    v-model="val.value"
                    label="Value"
                    placeholder="e.g. 64"
                    density="compact"
                    hide-details
                  />
                </VCol>
                <VCol cols="6" md="2">
                  <VSwitch
                    v-model="val.is_default"
                    label="Default"
                    density="compact"
                    hide-details
                  />
                </VCol>
                <VCol cols="6" md="1" class="text-end">
                  <VBtn
                    icon="tabler-trash"
                    variant="text"
                    color="error"
                    size="x-small"
                    @click="removeValue(optIndex, valIndex)"
                  />
                </VCol>
              </VRow>
              <div class="d-flex justify-end mt-1 mb-1">
                <VBtn
                  variant="text"
                  color="info"
                  size="x-small"
                  prepend-icon="tabler-calculator"
                  :disabled="!val.monthly_price || Number(val.monthly_price) <= 0"
                  @click="autoComputeValuePricing(optIndex, valIndex)"
                >
                  Auto-compute
                </VBtn>
              </div>
              <VRow>
                <VCol
                  v-for="cycle in pricingCycles"
                  :key="cycle.key"
                  cols="6"
                  md="2"
                >
                  <VTextField
                    v-model.number="(val as Record<string, unknown>)[cycle.key]"
                    :label="cycle.label"
                    type="number"
                    step="0.01"
                    min="0"
                    density="compact"
                    prefix="$"
                    hide-details
                  />
                </VCol>
              </VRow>
            </VCard>
          </template>
        </VExpansionPanelText>
      </VExpansionPanel>
    </VExpansionPanels>

    <div v-else class="text-center py-6">
      <VIcon icon="tabler-adjustments" size="48" color="disabled" class="mb-2" />
      <div class="text-medium-emphasis mb-3">
        No options added yet
      </div>
    </div>

    <VBtn
      variant="tonal"
      color="primary"
      prepend-icon="tabler-plus"
      size="small"
      @click="addOption"
    >
      Add Option
    </VBtn>
  </div>
</template>
