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

interface PlanOption {
  id: number
  name: string
  service_type: string
}

interface Props {
  plans: PlanOption[]
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const typeOptions = [
  { title: 'Percentage', value: 'percentage' },
  { title: 'Fixed Amount', value: 'fixed' },
]

const planSelectItems = computed(() =>
  props.plans.map(plan => ({
    title: `${plan.name} (${plan.service_type})`,
    value: plan.id,
  })),
)

const form = useForm({
  code: '',
  type: '' as string,
  value: '' as string | number,
  max_uses: null as number | null,
  expires_at: '' as string,
  applies_to: [] as number[],
})

function generateCode(): void {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
  let code = 'EZ-'
  for (let i = 0; i < 8; i++) {
    code += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  form.code = code
}

const valueLabel = computed<string>(() => {
  if (form.type === 'percentage') {
    return 'Discount Percentage (%)'
  }
  return 'Discount Amount (USD)'
})

const valuePlaceholder = computed<string>(() => {
  if (form.type === 'percentage') {
    return 'e.g. 15'
  }
  return 'e.g. 5.00'
})

function submit(): void {
  form.post('/coupons', {
    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="/coupons" class="text-decoration-none">
            <VBtn icon="tabler-arrow-left" variant="text" size="small" />
          </Link>
          <span class="text-h4 font-weight-bold">Create Coupon</span>
        </div>
        <div class="text-body-2 text-medium-emphasis ms-10">
          Add a new discount coupon
        </div>
      </div>
    </div>

    <form @submit.prevent="submit">
      <VRow>
        <!-- Coupon Details -->
        <VCol cols="12" lg="8">
          <VCard title="Coupon Details" class="mb-6">
            <VCardText>
              <VRow>
                <VCol cols="12" md="8">
                  <VTextField
                    v-model="form.code"
                    label="Coupon Code"
                    placeholder="e.g. SAVE20"
                    :error-messages="form.errors.code"
                  />
                </VCol>
                <VCol cols="12" md="4" class="d-flex align-end">
                  <VBtn
                    variant="tonal"
                    color="primary"
                    prepend-icon="tabler-refresh"
                    block
                    @click="generateCode"
                  >
                    Auto-Generate
                  </VBtn>
                </VCol>
                <VCol cols="12" md="6">
                  <VSelect
                    v-model="form.type"
                    label="Discount Type"
                    :items="typeOptions"
                    placeholder="Select type"
                    :error-messages="form.errors.type"
                  />
                </VCol>
                <VCol cols="12" md="6">
                  <VTextField
                    v-model="form.value"
                    :label="valueLabel"
                    type="number"
                    step="0.01"
                    min="0"
                    :placeholder="valuePlaceholder"
                    :error-messages="form.errors.value"
                  />
                </VCol>
              </VRow>
            </VCardText>
          </VCard>

          <!-- Plan Restrictions -->
          <VCard title="Plan Restrictions" class="mb-6">
            <VCardText>
              <p class="text-body-2 text-medium-emphasis mb-4">
                Optionally restrict this coupon to specific plans. Leave empty to apply to all plans.
              </p>
              <VSelect
                v-model="form.applies_to"
                label="Applicable Plans"
                :items="planSelectItems"
                placeholder="All Plans (no restriction)"
                multiple
                chips
                closable-chips
                :error-messages="form.errors.applies_to"
              />
            </VCardText>
          </VCard>
        </VCol>

        <!-- Sidebar -->
        <VCol cols="12" lg="4">
          <VCard title="Limits & Expiry" class="mb-6">
            <VCardText>
              <VTextField
                v-model="form.max_uses"
                label="Max Uses"
                type="number"
                min="1"
                placeholder="Unlimited"
                :error-messages="form.errors.max_uses"
                class="mb-4"
              />
              <VTextField
                v-model="form.expires_at"
                label="Expiry Date"
                type="datetime-local"
                :error-messages="form.errors.expires_at"
              />
            </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 Coupon
              </VBtn>
              <Link href="/coupons" class="text-decoration-none">
                <VBtn
                  variant="outlined"
                  block
                >
                  Cancel
                </VBtn>
              </Link>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>
    </form>
  </div>
</template>
