<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 * as z from 'zod'
const emit = defineEmits<{
  (e: 'organizationCreated', id: string | undefined): void
}>()

const { createOrganization } = useOrganizationStore()
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() {
  loading.value = true

  if (!state.name || !state.slug) return

  const organization = await createOrganization(state.name, state.slug, state.logo)
  emit('organizationCreated', organization.data?.id)
  loading.value = false
  open.value = false
}
</script>
