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

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

interface Props {
  coupon: Coupon
  plans: PlanOption[]
  redemptions: CouponRedemption[]
}

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,
  })),
)

function formatExpiresAt(dateStr: string | null): string {
  if (!dateStr) {
    return ''
  }
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day}T${hours}:${minutes}`
}

const form = useForm({
  code: props.coupon.code,
  type: props.coupon.type,
  value: props.coupon.value,
  max_uses: props.coupon.max_uses,
  expires_at: formatExpiresAt(props.coupon.expires_at),
  applies_to: props.coupon.applies_to ?? [],
})

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 resolveCouponStatus(): { label: string; color: StatusColor } {
  if (!props.coupon.active) {
    return { label: 'Inactive', color: 'error' }
  }
  if (props.coupon.expires_at && new Date(props.coupon.expires_at) < new Date()) {
    return { label: 'Expired', color: 'secondary' }
  }
  if (props.coupon.max_uses !== null && props.coupon.times_used >= props.coupon.max_uses) {
    return { label: 'Exhausted', color: 'warning' }
  }
  return { label: 'Active', color: 'success' }
}

function formatDate(dateString: string): string {
  const date = new Date(dateString)
  return date.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  })
}

const formattedCreatedAt = computed<string>(() => formatDate(props.coupon.created_at))

function submit(): void {
  form.put(`/coupons/${props.coupon.id}`, {
    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">Edit Coupon</span>
        </div>
        <div class="text-body-2 text-medium-emphasis ms-10">
          Update coupon "{{ coupon.code }}"
        </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">
                  <VTextField
                    v-model="form.code"
                    label="Coupon Code"
                    placeholder="e.g. SAVE20"
                    :error-messages="form.errors.code"
                  />
                </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>

          <!-- Redemption History Link -->
          <VCard class="mb-6">
            <VCardText class="d-flex align-center justify-space-between">
              <div class="d-flex align-center gap-3">
                <VAvatar color="primary" variant="tonal" size="40" rounded>
                  <VIcon icon="tabler-receipt" size="20" />
                </VAvatar>
                <div>
                  <div class="text-body-1 font-weight-medium">
                    Redemption History
                  </div>
                  <div class="text-body-2 text-medium-emphasis">
                    {{ redemptions.length }} redemption{{ redemptions.length !== 1 ? 's' : '' }} recorded
                  </div>
                </div>
              </div>
              <Link :href="`/coupons/${coupon.id}`" class="text-decoration-none">
                <VBtn
                  color="primary"
                  variant="tonal"
                  prepend-icon="tabler-eye"
                  size="small"
                >
                  View All
                </VBtn>
              </Link>
            </VCardText>
          </VCard>
        </VCol>

        <!-- Sidebar -->
        <VCol cols="12" lg="4">
          <!-- Coupon Info -->
          <VCard title="Coupon 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="resolveCouponStatus().color"
                  size="small"
                >
                  {{ resolveCouponStatus().label }}
                </VChip>
              </div>
              <div class="d-flex justify-space-between align-center mb-3">
                <span class="text-body-2 text-medium-emphasis">Times Used</span>
                <span class="text-body-2 font-weight-medium">{{ coupon.times_used }}</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>

          <!-- Limits & Expiry -->
          <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"
              >
                Update Coupon
              </VBtn>
              <Link href="/coupons" class="text-decoration-none">
                <VBtn
                  variant="outlined"
                  block
                >
                  Cancel
                </VBtn>
              </Link>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>
    </form>
  </div>
</template>
