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

defineOptions({ layout: AdminLayout })

interface FeatureRow {
  key: string
  value: string
}

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

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

const form = useForm({
  name: '',
  slug: '',
  description: '',
  service_type: '' as string,
  price: '' as string | number,
  billing_cycle: '' as string,
  features: [] as FeatureRow[],
  stock_quantity: null as number | null,
  sort_order: 0,
})

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

let slugManuallyEdited = false

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.post('/plans', {
    preserveScroll: true,
  })
}
</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">Create Plan</span>
        </div>
        <div class="text-body-2 text-medium-emphasis ms-10">
          Add a new service plan to your catalog
        </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>
        </VCol>

        <!-- Sidebar -->
        <VCol cols="12" lg="4">
          <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"
              >
                Create Plan
              </VBtn>
              <Link href="/plans" class="text-decoration-none">
                <VBtn
                  variant="outlined"
                  block
                >
                  Cancel
                </VBtn>
              </Link>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>
    </form>
  </div>
</template>
