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

const props = defineProps<{
  eventId: string
}>()

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

const eventIdRef = computed(() => props.eventId)

const form = ref({
  name: '',
  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' },
]

function resetForm() {
  form.value = {
    name: '',
    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,
        type: form.value.type,
        crew_auto_accepts: form.value.crew_auto_accepts,
        responder_self_checkin: form.value.responder_self_checkin,
      },
      {
        onSuccess: () => {
          modelValue.value = false
          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]]),
            )
          }
        },
      },
    )
  })
}
</script>

<template>
  <VDialog
    v-model="modelValue"
    max-width="500"
    @after-leave="resetForm"
  >
    <VCard title="Sectie aanmaken">
      <VCardText>
        <VForm
          ref="refVForm"
          @submit.prevent="onSubmit"
        >
          <VRow>
            <VCol cols="12">
              <AppTextField
                v-model="form.name"
                label="Naam"
                :rules="[requiredValidator]"
                :error-messages="errors.name"
                autofocus
              />
            </VCol>
            <VCol cols="12">
              <AppSelect
                v-model="form.type"
                label="Type"
                :items="typeOptions"
                :error-messages="errors.type"
              />
            </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>
        </VForm>
      </VCardText>
      <VCardActions>
        <VSpacer />
        <VBtn
          variant="text"
          @click="modelValue = false"
        >
          Annuleren
        </VBtn>
        <VBtn
          color="primary"
          :loading="isPending"
          @click="onSubmit"
        >
          Aanmaken
        </VBtn>
      </VCardActions>
    </VCard>
  </VDialog>
</template>
