<script setup lang="ts">
import { VForm } from 'vuetify/components/VForm'
import { useCreateCompany, useUpdateCompany } from '@/composables/api/useCompanies'
import { requiredValidator, emailValidator } from '@core/utils/validators'
import type { Company } from '@/types/organisation'

const props = defineProps<{
  orgId: string
  company?: Company | null
}>()

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

const orgIdRef = computed(() => props.orgId)

const isEdit = computed(() => !!props.company)

const form = ref({
  name: '',
  type: 'supplier' as Company['type'],
  contact_name: '',
  contact_email: '',
  contact_phone: '',
})

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

const { mutate: createCompany, isPending: isCreating } = useCreateCompany(orgIdRef)
const { mutate: updateCompany, isPending: isUpdating } = useUpdateCompany(orgIdRef)

const isPending = computed(() => isCreating.value || isUpdating.value)

const typeOptions = [
  { title: 'Leverancier', value: 'supplier' },
  { title: 'Partner', value: 'partner' },
  { title: 'Bureau', value: 'agency' },
  { title: 'Locatie', value: 'venue' },
  { title: 'Overig', value: 'other' },
]

watch(() => props.company, (c) => {
  if (c) {
    form.value = {
      name: c.name,
      type: c.type,
      contact_name: c.contact_name ?? '',
      contact_email: c.contact_email ?? '',
      contact_phone: c.contact_phone ?? '',
    }
  }
}, { immediate: true })

function resetForm() {
  form.value = {
    name: '',
    type: 'supplier',
    contact_name: '',
    contact_email: '',
    contact_phone: '',
  }
  errors.value = {}
  refVForm.value?.resetValidation()
}

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

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

    errors.value = {}

    const payload = {
      name: form.value.name,
      type: form.value.type,
      contact_name: form.value.contact_name || null,
      contact_email: form.value.contact_email || null,
      contact_phone: form.value.contact_phone || null,
    }

    const onSuccess = () => {
      modelValue.value = false
      emit('saved')
      resetForm()
    }

    const 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 }
      }
    }

    if (isEdit.value && props.company) {
      updateCompany({ id: props.company.id, ...payload }, { onSuccess, onError })
    }
    else {
      createCompany(payload, { onSuccess, onError })
    }
  })
}
</script>

<template>
  <VDialog
    v-model="modelValue"
    max-width="550"
    @after-leave="resetForm"
  >
    <VCard :title="isEdit ? 'Bedrijf bewerken' : 'Bedrijf toevoegen'">
      <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">
              <AppSelect
                v-model="form.type"
                label="Type"
                :items="typeOptions"
                :rules="[requiredValidator]"
                :error-messages="errors.type"
              />
            </VCol>
            <VCol cols="12">
              <AppTextField
                v-model="form.contact_name"
                label="Contactpersoon"
                :error-messages="errors.contact_name"
                autocomplete="one-time-code"
              />
            </VCol>
            <VCol cols="12">
              <AppTextField
                v-model="form.contact_email"
                label="E-mail"
                type="email"
                :rules="form.contact_email ? [emailValidator] : []"
                :error-messages="errors.contact_email"
              />
            </VCol>
            <VCol cols="12">
              <AppTextField
                v-model="form.contact_phone"
                label="Telefoon"
                type="tel"
                :error-messages="errors.contact_phone"
              />
            </VCol>
          </VRow>
        </VCardText>
        <VCardActions>
          <VSpacer />
          <VBtn
            variant="text"
            @click="modelValue = false"
          >
            Annuleren
          </VBtn>
          <VBtn
            type="submit"
            color="primary"
            :loading="isPending"
          >
            {{ isEdit ? 'Opslaan' : 'Toevoegen' }}
          </VBtn>
        </VCardActions>
      </VForm>
    </VCard>
  </VDialog>
</template>
