<script setup lang="ts">
import { VForm } from 'vuetify/components/VForm'
import { useCreateSection, useSectionCategories } from '@/composables/api/useSections'
import { useAuthStore } from '@/stores/useAuthStore'
import { requiredValidator } from '@core/utils/validators'
import type { SectionType } from '@/types/section'

const props = withDefaults(defineProps<{
  eventId: string
  isSubEvent?: boolean
  nextSortOrder?: number
}>(), {
  isSubEvent: false,
  nextSortOrder: 0,
})

const emit = defineEmits<{
  created: [payload: { name: string; redirectedToParent: boolean; parentEventName?: string }]
}>()

const modelValue = defineModel<boolean>({ required: true })

const eventIdRef = computed(() => props.eventId)
const authStore = useAuthStore()
const orgId = computed(() => authStore.currentOrganisation?.id ?? '')
const { data: categorySuggestions } = useSectionCategories(orgId)

const form = ref({
  name: '',
  category: null as string | null,
  icon: null as string | null,
  type: 'standard' as SectionType,
  crew_auto_accepts: false,
  responder_self_checkin: true,
})

const errors = ref<Record<string, string>>({})
const refVForm = ref<VForm>()

const { mutate: createSection, isPending } = useCreateSection(eventIdRef)

const typeOptions = [
  { title: 'Standaard', value: 'standard' },
  { title: 'Overkoepelend', value: 'cross_event' },
]

const showCrossEventHint = computed(() =>
  props.isSubEvent && form.value.type === 'cross_event',
)

function resetForm() {
  form.value = {
    name: '',
    category: null,
    icon: null,
    type: 'standard',
    crew_auto_accepts: false,
    responder_self_checkin: true,
  }
  errors.value = {}
  refVForm.value?.resetValidation()
}

function onSubmit() {
  refVForm.value?.validate().then(({ valid }) => {
    if (!valid) return

    errors.value = {}

    createSection(
      {
        name: form.value.name,
        category: form.value.category || null,
        icon: form.value.icon || null,
        type: form.value.type,
        sort_order: props.nextSortOrder,
        crew_auto_accepts: form.value.crew_auto_accepts,
        responder_self_checkin: form.value.responder_self_checkin,
      },
      {
        onSuccess: (result) => {
          modelValue.value = false
          emit('created', {
            name: result.section.name,
            redirectedToParent: result.redirectedToParent,
            parentEventName: result.parentEventName,
          })
          resetForm()
        },
        onError: (err: any) => {
          const data = err.response?.data
          if (data?.errors) {
            errors.value = Object.fromEntries(
              Object.entries(data.errors).map(([k, v]) => [k, (v as string[])[0]]),
            )
          }
          else if (data?.message) {
            errors.value = { type: data.message }
          }
        },
      },
    )
  })
}
</script>

<template>
  <VDialog
    v-model="modelValue"
    max-width="500"
    @after-leave="resetForm"
  >
    <VCard title="Sectie aanmaken">
      <VForm
        ref="refVForm"
        @submit.prevent="onSubmit"
      >
        <VCardText>
          <VRow>
            <VCol cols="12">
              <AppTextField
                v-model="form.name"
                label="Naam"
                :rules="[requiredValidator]"
                :error-messages="errors.name"
                autofocus
                autocomplete="one-time-code"
              />
            </VCol>
            <VCol cols="12">
              <VCombobox
                v-model="form.category"
                label="Categorie"
                :items="categorySuggestions ?? []"
                placeholder="Bijv. Bar, Podium, Operationeel..."
                clearable
                :error-messages="errors.category"
                autocomplete="one-time-code"
              />
            </VCol>
            <VCol cols="12">
              <div class="d-flex align-center gap-x-2">
                <AppTextField
                  v-model="form.icon"
                  label="Icoon"
                  placeholder="tabler-beer"
                  clearable
                  :error-messages="errors.icon"
                  class="flex-grow-1"
                  autocomplete="one-time-code"
                />
                <VIcon
                  v-if="form.icon"
                  :icon="form.icon"
                  size="24"
                />
              </div>
            </VCol>
            <VCol cols="12">
              <AppSelect
                v-model="form.type"
                label="Type"
                :items="typeOptions"
                :error-messages="errors.type"
              />
              <VAlert
                v-if="showCrossEventHint"
                type="info"
                variant="tonal"
                density="compact"
                class="mt-2"
              >
                Deze sectie wordt automatisch aangemaakt op festival-niveau en is zichtbaar in alle programmaonderdelen.
              </VAlert>
            </VCol>
            <VCol cols="12">
              <VSwitch
                v-model="form.crew_auto_accepts"
                label="Crew auto-accepteren"
                hint="Toewijzingen worden automatisch goedgekeurd"
                persistent-hint
              />
            </VCol>
            <VCol cols="12">
              <VSwitch
                v-model="form.responder_self_checkin"
                label="Zelfstandig inchecken"
                hint="Vrijwilligers kunnen zelf inchecken via QR"
                persistent-hint
              />
            </VCol>
          </VRow>
        </VCardText>
        <VCardActions>
          <VSpacer />
          <VBtn
            variant="text"
            @click="modelValue = false"
          >
            Annuleren
          </VBtn>
          <VBtn
            type="submit"
            color="primary"
            :loading="isPending"
          >
            Aanmaken
          </VBtn>
        </VCardActions>
      </VForm>
    </VCard>
  </VDialog>
</template>
