<template>
  <UModal
    v-model:open="open"
    title="New Organization"
    description="Create a new organization to collaborate with your team"
  >
    <template #default>
      <UButton icon="i-heroicons-plus" @click="open = true"> Organisation erstellen </UButton>
    </template>

    <template #body>
      <UForm :state="state" :schema="schema" class="space-y-4" @submit="onSubmit">
        <UFormField label="Name" name="name">
          <UInput v-model="state.name" class="w-full" />
        </UFormField>

        <UFormField label="Slug" name="slug">
          <UInput v-model="state.slug" class="w-full" @input="isSlugEdited = true" />
        </UFormField>

        <UFormField label="Logo (optional)" name="logo">
          <input type="file" accept="image/*" @change="handleLogoChange" />
          <img v-if="state.logo" :src="state.logo" alt="Logo preview" class="w-16 h-16 object-cover mt-2" />
        </UFormField>
        <div class="flex justify-end gap-2">
          <UButton type="submit" :loading="loading">
            {{ loading ? 'Creating...' : 'Create' }}
          </UButton>
        </div>
      </UForm>
    </template>
  </UModal>
</template>

<script setup lang="ts">
import type { FormSubmitEvent } from '@nuxt/ui'
import * as z from 'zod'

const emit = defineEmits(['formSubmitted'])

const open = ref(false)
const loading = ref(false)
const isSlugEdited = ref(false)

type Schema = z.output<typeof schema>

const schema = z.object({
  name: z.string().min(2, 'Too short'),
  slug: z.string().min(2, 'Too short'),
  logo: z.string().optional()
})

const state = reactive<Partial<Schema>>({
  name: undefined,
  slug: undefined,
  logo: undefined
})

watch(
  () => state.name,
  (newName) => {
    if (!isSlugEdited.value) {
      state.slug = (newName ?? '').trim().toLowerCase().replace(/\s+/g, '-')
    }
  }
)

watch(open, (val) => {
  if (val) {
    state.name = ''
    state.slug = ''
    state.logo = undefined
    isSlugEdited.value = false
  }
})

function handleLogoChange(event: Event) {
  const input = event.target as HTMLInputElement
  const file = input?.files?.[0]
  if (!file) return

  const reader = new FileReader()
  reader.onload = () => {
    state.logo = reader.result as string
  }
  reader.readAsDataURL(file)
}

async function onSubmit(event: FormSubmitEvent<Schema>) {
  console.log('onSubmit', state)
  loading.value = true
  await organization.create(
    {
      name: event.data.name,
      slug: event.data.slug,
      logo: event.data.logo
    },
    {
      onSuccess: () => {
        useToast().add({ title: 'Organisation erfolgreich erstellt', color: 'success' })
        emit('formSubmitted', { name: state.name, slug: state.slug })
        open.value = false
      },
      onError: (ctx) => {
        useToast().add({
          title: 'Fehler bei der Erstellung der Organisation',
          description: ctx.error.message,
          color: 'error'
        })
      },
      onResponse: () => {
        loading.value = false
      }
    }
  )
}
</script>
