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

defineOptions({ layout: AdminLayout })

interface EmailStep {
  delay_days: number | string
  subject: string
  body: string
}

const offerTypeOptions = [
  { title: 'Discount (%)', value: 'discount' },
  { title: 'Account Credit ($)', value: 'credit' },
  { title: 'Free Upgrade', value: 'free_upgrade' },
  { title: 'None', value: 'none' },
]

const statusOptions = [
  { title: 'Active', value: 'active' },
  { title: 'Paused', value: 'paused' },
  { title: 'Archived', value: 'archived' },
]

const cancellationReasonOptions = [
  { title: 'Any (Catch-all)', value: '' },
  { title: 'Too expensive', value: 'Too expensive' },
  { title: 'No longer needed', value: 'No longer needed' },
  { title: 'Switching to competitor', value: 'Switching to competitor' },
  { title: 'Poor performance', value: 'Poor performance' },
  { title: 'Missing features', value: 'Missing features' },
  { title: 'Technical issues', value: 'Technical issues' },
  { title: 'Other', value: 'Other' },
]

const form = useForm({
  name: '',
  cancellation_reason: '' as string,
  email_sequence: [
    { delay_days: 1, subject: '', body: '' },
  ] as EmailStep[],
  offer_type: 'none' as string,
  offer_value: null as number | null,
  offer_duration_days: null as number | null,
  coupon_code: '' as string,
  status: 'active' as string,
})

function addEmail(): void {
  const lastDelay = form.email_sequence.length > 0
    ? Number(form.email_sequence[form.email_sequence.length - 1].delay_days) + 3
    : 1
  form.email_sequence.push({ delay_days: lastDelay, subject: '', body: '' })
}

function removeEmail(index: number): void {
  form.email_sequence.splice(index, 1)
}

function moveEmail(index: number, direction: -1 | 1): void {
  const newIndex = index + direction
  if (newIndex < 0 || newIndex >= form.email_sequence.length) return
  const temp = form.email_sequence[index]
  form.email_sequence[index] = form.email_sequence[newIndex]
  form.email_sequence[newIndex] = temp
}

function submit(): void {
  form.transform((data) => ({
    ...data,
    cancellation_reason: data.cancellation_reason || null,
    coupon_code: data.coupon_code || null,
    email_sequence: data.email_sequence.map(e => ({
      ...e,
      delay_days: Number(e.delay_days),
    })),
  })).post('/winback-campaigns', {
    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="/winback-campaigns" class="text-decoration-none">
            <VBtn icon="tabler-arrow-left" variant="text" size="small" />
          </Link>
          <span class="text-h4 font-weight-bold">Create Win-back Campaign</span>
        </div>
        <div class="text-body-2 text-medium-emphasis ms-10">
          Set up an automated email sequence to re-engage cancelled customers
        </div>
      </div>
    </div>

    <form @submit.prevent="submit">
      <VRow>
        <VCol cols="12" lg="8">
          <!-- Campaign Details -->
          <VCard title="Campaign Details" class="mb-6">
            <VCardText>
              <VRow>
                <VCol cols="12" md="6">
                  <VTextField
                    v-model="form.name"
                    label="Campaign Name"
                    placeholder="e.g. Price-Sensitive Win-back"
                    :error-messages="form.errors.name"
                  />
                </VCol>
                <VCol cols="12" md="6">
                  <VSelect
                    v-model="form.cancellation_reason"
                    label="Target Cancellation Reason"
                    :items="cancellationReasonOptions"
                    :error-messages="form.errors.cancellation_reason"
                    hint="Leave as 'Any' to match cancellations without a specific campaign"
                    persistent-hint
                  />
                </VCol>
              </VRow>
            </VCardText>
          </VCard>

          <!-- Email Sequence -->
          <VCard title="Email Sequence" class="mb-6">
            <VCardText>
              <VAlert type="info" variant="tonal" density="compact" class="mb-4">
                Define the emails that will be sent to cancelled customers. The delay is measured from the previous email (or enrollment date for the first email).
              </VAlert>

              <div v-if="form.email_sequence.length === 0" class="text-center py-4">
                <VIcon icon="tabler-mail" size="40" color="disabled" class="mb-2" />
                <div class="text-medium-emphasis mb-3">
                  No emails in sequence yet. Add at least one email.
                </div>
              </div>

              <div
                v-for="(email, index) in form.email_sequence"
                :key="index"
                class="mb-4 pa-4 rounded border"
              >
                <div class="d-flex align-center justify-space-between mb-3">
                  <span class="text-body-1 font-weight-medium">Email {{ index + 1 }}</span>
                  <div class="d-flex gap-1">
                    <VBtn
                      icon="tabler-arrow-up"
                      variant="text"
                      size="x-small"
                      :disabled="index === 0"
                      @click="moveEmail(index, -1)"
                    />
                    <VBtn
                      icon="tabler-arrow-down"
                      variant="text"
                      size="x-small"
                      :disabled="index === form.email_sequence.length - 1"
                      @click="moveEmail(index, 1)"
                    />
                    <VBtn
                      icon="tabler-trash"
                      variant="text"
                      size="x-small"
                      color="error"
                      :disabled="form.email_sequence.length <= 1"
                      @click="removeEmail(index)"
                    />
                  </div>
                </div>
                <VRow>
                  <VCol cols="12" md="3">
                    <VTextField
                      v-model="email.delay_days"
                      label="Delay (days)"
                      type="number"
                      min="0"
                      density="compact"
                      :error-messages="form.errors[`email_sequence.${index}.delay_days`]"
                    />
                  </VCol>
                  <VCol cols="12" md="9">
                    <VTextField
                      v-model="email.subject"
                      label="Subject"
                      placeholder="Email subject line"
                      density="compact"
                      :error-messages="form.errors[`email_sequence.${index}.subject`]"
                    />
                  </VCol>
                  <VCol cols="12">
                    <VTextarea
                      v-model="email.body"
                      label="Body"
                      placeholder="Email body content..."
                      rows="3"
                      density="compact"
                      :error-messages="form.errors[`email_sequence.${index}.body`]"
                    />
                  </VCol>
                </VRow>
              </div>

              <VBtn
                variant="tonal"
                color="primary"
                prepend-icon="tabler-plus"
                size="small"
                @click="addEmail"
              >
                Add Email
              </VBtn>

              <div v-if="form.errors.email_sequence" class="text-error text-caption mt-2">
                {{ form.errors.email_sequence }}
              </div>
            </VCardText>
          </VCard>

          <!-- Offer Configuration -->
          <VCard title="Offer Configuration" class="mb-6">
            <VCardText>
              <VRow>
                <VCol cols="12" md="4">
                  <VSelect
                    v-model="form.offer_type"
                    label="Offer Type"
                    :items="offerTypeOptions"
                    :error-messages="form.errors.offer_type"
                  />
                </VCol>
                <VCol v-if="form.offer_type !== 'none'" cols="12" md="4">
                  <VTextField
                    v-model="form.offer_value"
                    :label="form.offer_type === 'discount' ? 'Discount (%)' : 'Credit Amount ($)'"
                    type="number"
                    step="0.01"
                    min="0"
                    :error-messages="form.errors.offer_value"
                  />
                </VCol>
                <VCol v-if="form.offer_type !== 'none'" cols="12" md="4">
                  <VTextField
                    v-model="form.offer_duration_days"
                    label="Offer Duration (days)"
                    type="number"
                    min="1"
                    :error-messages="form.errors.offer_duration_days"
                  />
                </VCol>
                <VCol v-if="form.offer_type !== 'none'" cols="12" md="4">
                  <VTextField
                    v-model="form.coupon_code"
                    label="Coupon Code"
                    placeholder="e.g. COMEBACK20"
                    :error-messages="form.errors.coupon_code"
                  />
                </VCol>
              </VRow>
            </VCardText>
          </VCard>
        </VCol>

        <!-- Sidebar -->
        <VCol cols="12" lg="4">
          <VCard title="Status" class="mb-6">
            <VCardText>
              <VSelect
                v-model="form.status"
                label="Campaign Status"
                :items="statusOptions"
                :error-messages="form.errors.status"
              />
            </VCardText>
          </VCard>

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