<script setup lang="ts">
import { VForm } from 'vuetify/components/VForm'
import { useCreateTimeSlot } from '@/composables/api/useTimeSlots'
import { requiredValidator } from '@core/utils/validators'

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

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

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

const form = ref({
  name: '',
  person_type: 'VOLUNTEER',
  date: '',
  start_time: '',
  end_time: '',
  duration_hours: null as number | null,
})

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

const { mutate: createTimeSlot, isPending } = useCreateTimeSlot(eventIdRef)

const personTypeOptions = [
  { title: 'Vrijwilliger', value: 'VOLUNTEER' },
  { title: 'Crew', value: 'CREW' },
  { title: 'Pers', value: 'PRESS' },
  { title: 'Fotograaf', value: 'PHOTO' },
  { title: 'Partner', value: 'PARTNER' },
]

// Auto-calculate duration from start/end time
watch(
  () => [form.value.start_time, form.value.end_time],
  ([start, end]) => {
    if (start && end) {
      const [sh, sm] = start.split(':').map(Number)
      const [eh, em] = end.split(':').map(Number)
      let diff = (eh * 60 + em) - (sh * 60 + sm)
      if (diff < 0) diff += 24 * 60
      form.value.duration_hours = Math.round((diff / 60) * 100) / 100
    }
  },
)

function resetForm() {
  form.value = {
    name: '',
    person_type: 'VOLUNTEER',
    date: '',
    start_time: '',
    end_time: '',
    duration_hours: null,
  }
  errors.value = {}
  refVForm.value?.resetValidation()
}

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

    errors.value = {}

    createTimeSlot(
      {
        name: form.value.name,
        person_type: form.value.person_type,
        date: form.value.date,
        start_time: form.value.start_time,
        end_time: form.value.end_time,
        ...(form.value.duration_hours != null ? { duration_hours: form.value.duration_hours } : {}),
      },
      {
        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="550"
    @after-leave="resetForm"
  >
    <VCard title="Time Slot aanmaken">
      <VCardText>
        <VForm
          ref="refVForm"
          @submit.prevent="onSubmit"
        >
          <VRow>
            <VCol cols="12">
              <AppTextField
                v-model="form.name"
                label="Naam"
                placeholder="Dag 1 Avond - Vrijwilliger"
                :rules="[requiredValidator]"
                :error-messages="errors.name"
                autofocus
              />
            </VCol>
            <VCol cols="12">
              <AppSelect
                v-model="form.person_type"
                label="Persoonscategorie"
                :items="personTypeOptions"
                :rules="[requiredValidator]"
                :error-messages="errors.person_type"
              />
            </VCol>
            <VCol cols="12">
              <AppTextField
                v-model="form.date"
                label="Datum"
                type="date"
                :rules="[requiredValidator]"
                :error-messages="errors.date"
              />
            </VCol>
            <VCol
              cols="12"
              sm="6"
            >
              <AppTextField
                v-model="form.start_time"
                label="Starttijd"
                type="time"
                :rules="[requiredValidator]"
                :error-messages="errors.start_time"
              />
            </VCol>
            <VCol
              cols="12"
              sm="6"
            >
              <AppTextField
                v-model="form.end_time"
                label="Eindtijd"
                type="time"
                :rules="[requiredValidator]"
                :error-messages="errors.end_time"
              />
            </VCol>
            <VCol cols="12">
              <AppTextField
                v-model.number="form.duration_hours"
                label="Duur (uren)"
                type="number"
                :error-messages="errors.duration_hours"
                hint="Automatisch berekend uit start- en eindtijd"
                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>
