<template>
  <div class="create-form">
    <div class="page-header">
      <NuxtLink to="/admin/series-management" class="back-link">&larr; Series</NuxtLink>
      <h1>Create New Series</h1>
      <p>Create a new event series to group related events together</p>
    </div>

    <div class="form-body">
      <!-- Error Summary -->
      <div v-if="formErrors.length > 0" class="error-box">
        <Icon name="heroicons:exclamation-circle" class="box-icon" />
        <div>
          <strong>Please fix the following errors:</strong>
          <ul>
            <li v-for="error in formErrors" :key="error">{{ error }}</li>
          </ul>
        </div>
      </div>

      <!-- Success Message -->
      <div v-if="showSuccessMessage" class="success-box">
        <Icon name="heroicons:check-circle" class="box-icon" />
        <div>
          <strong>Series created successfully!</strong>
        </div>
      </div>

      <form @submit.prevent="createSeries">
        <!-- Series Information -->
        <div class="form-section">
          <h2 class="section-heading">Series Information</h2>

          <div class="field">
            <label>
              Series Title <span class="required">*</span>
            </label>
            <input
              v-model="seriesForm.title"
              type="text"
              placeholder="e.g., Cooperative Game Development Fundamentals"
              required
              :class="{ 'has-error': fieldErrors.title }"
              @input="generateSlugFromTitle"
            />
            <p v-if="fieldErrors.title" class="field-error">{{ fieldErrors.title }}</p>
          </div>

          <div v-if="generatedSlug" class="field">
            <label>Generated Series ID</label>
            <div class="slug-display">
              {{ generatedSlug }}
            </div>
            <p class="help-text">
              This unique identifier will be automatically generated from your title
            </p>
          </div>

          <div class="field">
            <label>
              Series Description <span class="required">*</span>
            </label>
            <textarea
              v-model="seriesForm.description"
              placeholder="Describe what the series covers and its goals"
              required
              rows="4"
              :class="{ 'has-error': fieldErrors.description }"
            ></textarea>
            <p v-if="fieldErrors.description" class="field-error">{{ fieldErrors.description }}</p>
          </div>

          <div class="form-grid">
            <div class="field">
              <label>Series Type</label>
              <select v-model="seriesForm.type">
                <option value="workshop_series">Workshop Series</option>
                <option value="recurring_meetup">Recurring Meetup</option>
                <option value="multi_day">Multi-Day Event</option>
                <option value="course">Course</option>
                <option value="tournament">Tournament</option>
              </select>
            </div>

            <div class="field">
              <label>Total Events Planned</label>
              <input
                v-model.number="seriesForm.totalEvents"
                type="number"
                min="1"
                placeholder="e.g., 4"
              />
              <p class="help-text">How many events will be in this series? (optional)</p>
            </div>
          </div>
        </div>

        <!-- Form Actions -->
        <div class="form-actions">
          <NuxtLink
            to="/admin/series-management"
            class="btn"
          >
            Cancel
          </NuxtLink>

          <div class="form-actions-right">
            <button
              type="button"
              @click="createAndAddEvent"
              :disabled="creating"
              class="btn"
            >
              {{ creating ? 'Creating...' : 'Create & Add Event' }}
            </button>

            <button
              type="submit"
              :disabled="creating"
              class="btn btn-primary"
            >
              {{ creating ? 'Creating...' : 'Create Series' }}
            </button>
          </div>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
definePageMeta({
  layout: 'admin',
  middleware: 'admin',
})

const router = useRouter()

const creating = ref(false)
const showSuccessMessage = ref(false)
const formErrors = ref([])
const fieldErrors = ref({})
const generatedSlug = ref('')

const seriesForm = reactive({
  title: '',
  description: '',
  type: 'workshop_series',
  totalEvents: null
})

// Generate slug from title
const generateSlug = (text) => {
  return text
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9\s-]/g, '') // Remove special characters except spaces and dashes
    .replace(/\s+/g, '-') // Replace spaces with dashes
    .replace(/-+/g, '-') // Replace multiple dashes with single dash
    .replace(/^-+|-+$/g, '') // Remove leading/trailing dashes
}

const generateSlugFromTitle = () => {
  if (seriesForm.title) {
    generatedSlug.value = generateSlug(seriesForm.title)
  } else {
    generatedSlug.value = ''
  }
}

const validateForm = () => {
  formErrors.value = []
  fieldErrors.value = {}

  if (!seriesForm.title.trim()) {
    formErrors.value.push('Series title is required')
    fieldErrors.value.title = 'Please enter a series title'
  }

  if (!seriesForm.description.trim()) {
    formErrors.value.push('Series description is required')
    fieldErrors.value.description = 'Please provide a description for the series'
  }

  if (!generatedSlug.value) {
    formErrors.value.push('Series title must generate a valid ID')
    fieldErrors.value.title = 'Please enter a title that can generate a valid series ID'
  }

  return formErrors.value.length === 0
}

const createSeries = async (redirectAfter = true) => {
  if (!validateForm()) {
    window.scrollTo({ top: 0, behavior: 'smooth' })
    return false
  }

  creating.value = true
  try {
    const response = await $fetch('/api/admin/series', {
      method: 'POST',
      body: {
        ...seriesForm,
        id: generatedSlug.value
      }
    })

    showSuccessMessage.value = true
    setTimeout(() => { showSuccessMessage.value = false }, 5000)

    if (redirectAfter) {
      setTimeout(() => {
        router.push('/admin/series-management')
      }, 1500)
    }

    return response.data
  } catch (error) {
    console.error('Failed to create series:', error)
    formErrors.value = [`Failed to create series: ${error.data?.statusMessage || error.message}`]
    window.scrollTo({ top: 0, behavior: 'smooth' })
    return false
  } finally {
    creating.value = false
  }
}

const createAndAddEvent = async () => {
  const series = await createSeries(false)
  if (series) {
    // Navigate to event creation with series pre-filled
    const seriesData = {
      series: {
        isSeriesEvent: true,
        id: generatedSlug.value,
        title: seriesForm.title,
        description: seriesForm.description,
        type: seriesForm.type,
        position: 1,
        totalEvents: seriesForm.totalEvents
      }
    }

    sessionStorage.setItem('seriesEventData', JSON.stringify(seriesData))
    router.push('/admin/events/create?series=true')
  }
}
</script>

<style scoped>
.create-form {
  max-width: 800px;
  margin: 0 auto;
}

.page-header {
  padding: 28px 28px 20px;
  border-bottom: 1px dashed var(--border);
}

.page-header h1 {
  font-family: 'Brygada 1918', serif;
  font-size: 24px;
  font-weight: 500;
  color: var(--text-bright);
  line-height: 1.2;
  margin-bottom: 4px;
}

.page-header p { font-size: 12px; color: var(--text-dim); }

.back-link {
  font-size: 12px;
  color: var(--candle);
  text-decoration: none;
  margin-bottom: 8px;
  display: inline-block;
}
.back-link:hover { text-decoration: underline; }

.form-body { padding: 24px 28px; }

.form-section { margin-bottom: 32px; }

.section-heading {
  font-family: 'Brygada 1918', serif;
  font-size: 16px;
  font-weight: 500;
  color: var(--text-bright);
  padding-bottom: 10px;
  border-bottom: 1px dashed var(--border);
  margin-bottom: 16px;
}

.error-box {
  display: flex;
  gap: 10px;
  padding: 16px 20px;
  border: 1px dashed var(--ember);
  margin-bottom: 20px;
  font-size: 12px;
  color: var(--ember);
}

.error-box ul { margin-top: 6px; padding: 0; list-style: none; }
.error-box li::before { content: '\2022\00a0'; }

.success-box {
  display: flex;
  gap: 10px;
  padding: 16px 20px;
  border: 1px dashed var(--candle);
  margin-bottom: 20px;
  font-size: 12px;
  color: var(--candle);
}

.box-icon {
  width: 16px;
  height: 16px;
  flex-shrink: 0;
  margin-top: 1px;
}

.required { color: var(--ember); }

.has-error { border-color: var(--ember) !important; }

.help-text { font-size: 11px; color: var(--text-faint); margin-top: 4px; }
.field-error { font-size: 11px; color: var(--ember); margin-top: 4px; }

.slug-display {
  padding: 5px 8px;
  font-family: 'Commit Mono', monospace;
  font-size: 13px;
  color: var(--text-bright);
  background: var(--surface);
  border: 1px dashed var(--border);
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.form-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20px;
  border-top: 1px dashed var(--border);
  margin-top: 32px;
}

.form-actions-right {
  display: flex;
  gap: 8px;
}

@media (max-width: 768px) {
  .page-header { padding: 24px 20px 16px; }
  .form-body { padding: 20px; }
  .form-grid { grid-template-columns: 1fr; }
}
</style>
