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

defineOptions({ layout: AdminLayout })

interface FeatureRow {
  key: string
  value: string
}

interface Props {
  plan: Plan & { created_at: string }
  subscribersCount: number
}

const props = defineProps<Props>()

const serviceTypeOptions = [
  { title: 'VPS', value: 'vps' },
  { title: 'Dedicated', value: 'dedicated' },
  { title: 'Hosting', value: 'hosting' },
  { title: 'MySQL', value: 'mysql' },
  { title: 'Game Server', value: 'game' },
  { title: 'Backups', value: 'backups' },
]

const billingCycleOptions = [
  { title: 'Monthly', value: 'monthly' },
  { title: 'Quarterly', value: 'quarterly' },
  { title: 'Semi-Annual', value: 'semi_annual' },
  { title: 'Annual', value: 'annual' },
]

function featuresFromPlan(features: Record<string, string> | null): FeatureRow[] {
  if (!features) {
    return []
  }
  return Object.entries(features).map(([key, value]) => ({ key, value }))
}

const form = useForm({
  name: props.plan.name,
  slug: props.plan.slug,
  description: props.plan.description ?? '',
  service_type: props.plan.service_type,
  price: props.plan.price,
  billing_cycle: props.plan.billing_cycle,
  features: featuresFromPlan(props.plan.features),
  provisioning_config: {
    package_id: props.plan.provisioning_config?.package_id ?? null,
    hypervisor_id: props.plan.provisioning_config?.hypervisor_id ?? null,
  },
  stock_quantity: props.plan.stock_quantity,
  sort_order: props.plan.sort_order,
  days_to_suspend: props.plan.days_to_suspend ?? null,
  days_to_terminate: props.plan.days_to_terminate ?? null,
  auto_suspend_enabled: props.plan.auto_suspend_enabled ?? true,
  auto_terminate_enabled: props.plan.auto_terminate_enabled ?? true,
})

const showProvisioningConfig = computed<boolean>(() => ['vps', 'dedicated', 'hosting', 'game'].includes(form.service_type))

function slugify(text: string): string {
  return text
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '')
}

let slugManuallyEdited = true // Start as true since slug is pre-populated

watch(() => form.name, (newName: string) => {
  if (!slugManuallyEdited) {
    form.slug = slugify(newName)
  }
})

function onSlugInput(): void {
  slugManuallyEdited = true
}

function addFeature(): void {
  form.features.push({ key: '', value: '' })
}

function removeFeature(index: number): void {
  form.features.splice(index, 1)
}

function submit(): void {
  form.put(`/plans/${props.plan.id}`, {
    preserveScroll: true,
  })
}

const formattedCreatedAt = computed<string>(() => {
  const date = new Date(props.plan.created_at)
  return date.toLocaleDateString('en-US', {
    month: 'long',
    day: 'numeric',
    year: 'numeric',
  })
})
</script>

<template>
  <div>
    <!-- Header -->
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="d-flex align-center gap-2 mb-1">
          <Link href="/plans" class="text-decoration-none">
            <VBtn icon="tabler-arrow-left" variant="text" size="small" />
          </Link>
          <span class="text-h4 font-weight-bold">Edit Plan</span>
        </div>
        <div class="text-body-2 text-medium-emphasis ms-10">
          Update plan details for "{{ plan.name }}"
        </div>
      </div>
    </div>

    <form @submit.prevent="submit">
      <VRow>
        <!-- Plan Details -->
        <VCol cols="12" lg="8">
          <VCard title="Plan Details" class="mb-6">
            <VCardText>
              <VRow>
                <VCol cols="12" md="6">
                  <VTextField
                    v-model="form.name"
                    label="Plan Name"
                    placeholder="e.g. Basic VPS"
                    :error-messages="form.errors.name"
                  />
                </VCol>
                <VCol cols="12" md="6">
                  <VTextField
                    v-model="form.slug"
                    label="Slug"
                    placeholder="e.g. basic-vps"
                    :error-messages="form.errors.slug"
                    @input="onSlugInput"
                  />
                </VCol>
                <VCol cols="12">
                  <VTextarea
                    v-model="form.description"
                    label="Description"
                    placeholder="Brief description of the plan..."
                    rows="3"
                    :error-messages="form.errors.description"
                  />
                </VCol>
              </VRow>
            </VCardText>
          </VCard>

          <!-- Pricing & Billing -->
          <VCard title="Pricing & Billing" class="mb-6">
            <VCardText>
              <VRow>
                <VCol cols="12" md="4">
                  <VSelect
                    v-model="form.service_type"
                    label="Service Type"
                    :items="serviceTypeOptions"
                    placeholder="Select type"
                    :error-messages="form.errors.service_type"
                  />
                </VCol>
                <VCol cols="12" md="4">
                  <VTextField
                    v-model="form.price"
                    label="Price (USD)"
                    type="number"
                    step="0.01"
                    min="0"
                    placeholder="0.00"
                    :error-messages="form.errors.price"
                  />
                </VCol>
                <VCol cols="12" md="4">
                  <VSelect
                    v-model="form.billing_cycle"
                    label="Billing Cycle"
                    :items="billingCycleOptions"
                    placeholder="Select cycle"
                    :error-messages="form.errors.billing_cycle"
                  />
                </VCol>
              </VRow>
            </VCardText>
          </VCard>

          <!-- Features -->
          <VCard title="Features" class="mb-6">
            <VCardText>
              <div v-if="form.features.length === 0" class="text-center py-4">
                <VIcon icon="tabler-list" size="40" color="disabled" class="mb-2" />
                <div class="text-medium-emphasis mb-3">
                  No features added yet
                </div>
              </div>

              <div
                v-for="(feature, index) in form.features"
                :key="index"
                class="mb-3"
              >
                <VRow align="center">
                  <VCol cols="12" md="5">
                    <VTextField
                      v-model="feature.key"
                      placeholder="Feature name (e.g. cpu, ram)"
                      density="compact"
                      hide-details
                    />
                  </VCol>
                  <VCol cols="12" md="5">
                    <VTextField
                      v-model="feature.value"
                      placeholder="Value (e.g. 2 vCPU, 4 GB)"
                      density="compact"
                      hide-details
                    />
                  </VCol>
                  <VCol cols="12" md="2">
                    <VBtn
                      icon="tabler-trash"
                      color="error"
                      variant="text"
                      size="small"
                      @click="removeFeature(index)"
                    />
                  </VCol>
                </VRow>
              </div>

              <VBtn
                variant="tonal"
                color="primary"
                prepend-icon="tabler-plus"
                size="small"
                @click="addFeature"
              >
                Add Feature
              </VBtn>
            </VCardText>
          </VCard>

          <!-- Provisioning Config -->
          <VCard v-if="showProvisioningConfig" title="Provisioning Config" class="mb-6">
            <VCardText>
              <VAlert type="info" variant="tonal" density="compact" class="mb-4">
                These settings link this plan to the provisioning platform. They are not shown to customers.
              </VAlert>
              <VRow>
                <VCol cols="12" md="6">
                  <VTextField
                    v-model.number="form.provisioning_config.package_id"
                    label="Package ID"
                    type="number"
                    min="1"
                    placeholder="e.g. 44"
                    hint="VirtFusion/SynergyCP/Enhance package ID"
                    persistent-hint
                  />
                </VCol>
                <VCol cols="12" md="6">
                  <VTextField
                    v-model.number="form.provisioning_config.hypervisor_id"
                    label="Hypervisor ID"
                    type="number"
                    min="1"
                    placeholder="e.g. 1"
                    hint="Target hypervisor/node (default: 1)"
                    persistent-hint
                  />
                </VCol>
              </VRow>
            </VCardText>
          </VCard>

          <!-- Lifecycle Settings -->
          <VCard title="Lifecycle Settings" class="mb-6">
            <VCardText>
              <VAlert type="info" variant="tonal" density="compact" class="mb-4">
                Override global suspension/termination timings for this plan. Leave empty to use global defaults.
              </VAlert>
              <VRow>
                <VCol cols="12" md="6">
                  <VTextField
                    v-model.number="form.days_to_suspend"
                    label="Days to Suspend"
                    type="number"
                    min="1"
                    placeholder="Use global default"
                    hint="Days past due before services are suspended"
                    persistent-hint
                    :error-messages="form.errors.days_to_suspend"
                  />
                </VCol>
                <VCol cols="12" md="6">
                  <VTextField
                    v-model.number="form.days_to_terminate"
                    label="Days to Terminate"
                    type="number"
                    min="1"
                    placeholder="Use global default"
                    hint="Days after suspension before services are terminated"
                    persistent-hint
                    :error-messages="form.errors.days_to_terminate"
                  />
                </VCol>
                <VCol cols="12" md="6">
                  <VSwitch
                    v-model="form.auto_suspend_enabled"
                    label="Auto-Suspend Enabled"
                    color="primary"
                    hide-details
                  />
                </VCol>
                <VCol cols="12" md="6">
                  <VSwitch
                    v-model="form.auto_terminate_enabled"
                    label="Auto-Terminate Enabled"
                    color="primary"
                    hide-details
                  />
                </VCol>
              </VRow>
            </VCardText>
          </VCard>
        </VCol>

        <!-- Sidebar -->
        <VCol cols="12" lg="4">
          <!-- Plan Info -->
          <VCard title="Plan Info" class="mb-6">
            <VCardText>
              <div class="d-flex justify-space-between align-center mb-3">
                <span class="text-body-2 text-medium-emphasis">Status</span>
                <VChip
                  :color="plan.status === 'active' ? 'success' : 'error'"
                  size="small"
                  class="text-capitalize"
                >
                  {{ plan.status }}
                </VChip>
              </div>
              <div class="d-flex justify-space-between align-center mb-3">
                <span class="text-body-2 text-medium-emphasis">Active Subscribers</span>
                <span class="text-body-2 font-weight-medium">{{ subscribersCount }}</span>
              </div>
              <div class="d-flex justify-space-between align-center">
                <span class="text-body-2 text-medium-emphasis">Created</span>
                <span class="text-body-2">{{ formattedCreatedAt }}</span>
              </div>
            </VCardText>
          </VCard>

          <!-- Inventory & Ordering -->
          <VCard title="Inventory & Ordering" class="mb-6">
            <VCardText>
              <VTextField
                v-model="form.stock_quantity"
                label="Stock Quantity"
                type="number"
                min="0"
                placeholder="Leave empty for unlimited"
                :error-messages="form.errors.stock_quantity"
                class="mb-4"
              />
              <VTextField
                v-model="form.sort_order"
                label="Sort Order"
                type="number"
                min="0"
                :error-messages="form.errors.sort_order"
              />
            </VCardText>
          </VCard>

          <!-- Actions -->
          <VCard>
            <VCardText>
              <VBtn
                type="submit"
                color="primary"
                block
                :loading="form.processing"
                :disabled="form.processing"
                prepend-icon="tabler-check"
                class="mb-3"
              >
                Update Plan
              </VBtn>
              <Link href="/plans" class="text-decoration-none">
                <VBtn
                  variant="outlined"
                  block
                >
                  Cancel
                </VBtn>
              </Link>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>
    </form>
  </div>
</template>
