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

const props = defineProps<{
  eventId: string
  section: FestivalSection | null
}>()

const emit = defineEmits<{
  updated: []
}>()

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,
  show_in_registration: false,
  registration_description: null as string | null,
})

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

const { mutate: updateSection, isPending } = useUpdateSection(eventIdRef)

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

// Pre-fill form when section changes or dialog opens
watch(
  () => props.section,
  (section) => {
    if (section) {
      form.value = {
        name: section.name,
        category: section.category,
        icon: section.icon,
        type: section.type,
        crew_auto_accepts: section.crew_auto_accepts,
        responder_self_checkin: section.responder_self_checkin,
        show_in_registration: section.show_in_registration,
        registration_description: section.registration_description,
      }
    }
  },
  { immediate: true },
)

function resetForm() {
  errors.value = {}
  refVForm.value?.resetValidation()
}

function onSubmit() {
  if (!props.section) return

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

    errors.value = {}

    updateSection(
      {
        id: props.section!.id,
        name: form.value.name,
        category: form.value.category || null,
        icon: form.value.icon || null,
        crew_auto_accepts: form.value.crew_auto_accepts,
        responder_self_checkin: form.value.responder_self_checkin,
        show_in_registration: form.value.show_in_registration,
        registration_description: form.value.registration_description || null,
      },
      {
        onSuccess: () => {
          modelValue.value = false
          emit('updated')
        },
        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 = { name: data.message }
          }
        },
      },
    )
  })
}
</script>

<template>
  <VDialog
    v-model="modelValue"
    max-width="500"
    @after-leave="resetForm"
  >
    <VCard title="Sectie bewerken">
      <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"
                disabled
                hint="Type kan niet worden gewijzigd na aanmaken"
                persistent-hint
              />
            </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>
            <VCol cols="12">
              <VSwitch
                v-model="form.show_in_registration"
                label="Toon in vrijwilligersregistratie"
                hint="Dit werkgebied verschijnt in het aanmeldformulier voor vrijwilligers"
                persistent-hint
              />
            </VCol>
            <VCol
              v-if="form.show_in_registration"
              cols="12"
            >
              <VTextarea
                v-model="form.registration_description"
                label="Beschrijving voor vrijwilligers"
                :counter="500"
                rows="2"
                auto-grow
                hint="Korte uitleg zodat vrijwilligers weten wat dit werkgebied inhoudt"
                persistent-hint
                :error-messages="errors.registration_description"
              />
            </VCol>
          </VRow>
        </VCardText>
        <VCardActions>
          <VSpacer />
          <VBtn
            variant="text"
            @click="modelValue = false"
          >
            Annuleren
          </VBtn>
          <VBtn
            type="submit"
            color="primary"
            :loading="isPending"
          >
            Opslaan
          </VBtn>
        </VCardActions>
      </VForm>
    </VCard>
  </VDialog>
</template>
