<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="organizationSchema" class="space-y-4" @submit="onCreateOrganizationSubmit">
        <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 { organizationSchema, type OrganizationSchema } from '~/types/schemas'

const { createOrganization } = useOrganizationStore()
const open = ref(false)
const loading = ref(false)
const isSlugEdited = ref(false)

const state = reactive<Partial<OrganizationSchema>>({
  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 onCreateOrganizationSubmit() {
  loading.value = true

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

  await createOrganization(state.name, state.slug, state.logo)
  loading.value = false
  open.value = false
}
</script>
