<template>
  <UForm
    :schema="schema"
    :state="form.state"
    class="space-y-6"
    @submit="onSubmit"
  >
    <UFormField
      :label="$t('superAdmin.newUser.nameLabel')"
      name="name"
      required
    >
      <UInput
        v-model="form.state.name"
        class="w-full"
        size="lg"
      />
    </UFormField>
    <UFormField
      :label="$t('superAdmin.newUser.emailLabel')"
      name="email"
      required
    >
      <UInput
        v-model="form.state.email"
        class="w-full"
        size="lg"
      />
    </UFormField>
    <UFormField
      :label="$t('superAdmin.newUser.passwordLabel')"
      name="password"
      required
    >
      <UInput
        ref="passwordInput"
        v-model="form.state.password"
        :type="copied ? 'text' : 'password'"
        class="w-full"
        size="lg"
        :ui="{ trailing: 'pr-1' }"
      >
        <template #trailing>
          <UTooltip
            :text="$t('superAdmin.newUser.generatePasswordTooltip')"
            :content="{ side: 'right' }"
          >
            <UButton
              color="neutral"
              variant="link"
              size="sm"
              icon="i-solar-star-bold-duotone"
              @click="generatePassword"
            />
          </UTooltip>
        </template>
      </UInput>
    </UFormField>
    <UFormField
      :label="$t('superAdmin.newUser.phoneNumberLabel')"
      name="phoneNumber"
    >
      <UInput
        v-model="form.state.phoneNumber"
        class="w-full"
        size="lg"
        :placeholder="$t('superAdmin.newUser.phoneNumberPlaceholder')"
      />
    </UFormField>
    <UFormField
      :label="$t('superAdmin.newUser.avatarLabel')"
      name="avatar"
    >
      <AppAvatarUploader
        v-model="form.state.avatarUrl"
        :avatar-size="'md'"
        @file-selected="handleFileSelected"
      />
    </UFormField>
    <UCheckbox
      v-model="form.state.emailVerified"
      size="lg"
      :label="$t('superAdmin.newUser.autoVerifyLabel')"
      :description="$t('superAdmin.newUser.autoVerifyDescription')"
    />
    <UButton
      :loading="form.isSubmitting.value"
      type="submit"
      :label="$t('superAdmin.newUser.submitButton')"
    />
  </UForm>
</template>

<script setup lang="ts">
import * as z from 'zod'
import type { FormSubmitEvent } from '@nuxt/ui'
import { useForm } from '../../composables/useForm'
import { useClipboard } from '@vueuse/core'
import { FetchError } from 'ofetch'

const emit = defineEmits(['user-created'])
const { copy, copied } = useClipboard({
  copiedDuring: 3000
})
const { t } = useI18n()
const log = useLogger('New User')

const schema = z.object({
  name: z.string().min(1, t('superAdmin.newUser.validation.nameRequired')),
  email: z.string().email(t('superAdmin.newUser.validation.invalidEmail')),
  password: z.string().min(8, t('superAdmin.newUser.validation.passwordMinLength')),
  emailVerified: z.boolean().optional(),
  avatarUrl: z.string().optional(),
  phoneNumber: z
    .string()
    .regex(
      /^\+[1-9]\d{1,14}$/,
      t('superAdmin.newUser.validation.phoneFormat')
    )
    .optional()
})

type Schema = z.output<typeof schema>

// Use form composable for consistent form handling
const form = useForm(schema, {
  name: undefined,
  email: undefined,
  phoneNumber: undefined,
  password: undefined,
  emailVerified: false,
  avatarUrl: undefined
})

const toast = useToast()
const selectedFile = ref<File | null>(null)

async function onSubmit(event: FormSubmitEvent<Schema>) {
  await form.handleFormSubmit(
    event,
    async (data: Schema) => {
      let filePath = ''

      if (selectedFile.value) {
        filePath = await uploadAvatar()
      }
      const payload = {
        ...data,
        avatarUrl: filePath || form.state.avatarUrl
      }
      const apiCall = useApiCall()
      const response = await apiCall('/api/super-admin/users', {
        method: 'POST',
        body: payload
      })
      toast.add({
        title: t('superAdmin.newUser.messages.success'),
        description: t('superAdmin.newUser.messages.successDescription', {
          name: form.state.name,
          verification: !form.state.emailVerified ? t('superAdmin.newUser.messages.successVerification') : ''
        }),
        color: 'success',
        duration: 5000
      })

      // Reset form and file selection after successful submission
      form.reset()
      selectedFile.value = null

      // Emit event to notify parent component
      emit('user-created', response)
    },
    {
      onError: (error: unknown) => {
        const errorMessage = (error instanceof FetchError ? error.data?.message : null) || t('superAdmin.newUser.messages.error')
        toast.add({
          title: t('superAdmin.newUser.messages.errorTitle'),
          description: errorMessage,
          color: 'error',
          duration: 5000
        })
        log.error('Failed to create user:', error)
      },
      resetOnSuccess: false // We handle reset manually to also clear selectedFile
    }
  )
}

const passwordInput = ref<HTMLInputElement | null>(null)
async function generatePassword() {
  form.setField('password', Math.random().toString(36).substring(2, 15))
  await copy(form.state.password!)
  toast.add({
    title: t('superAdmin.newUser.messages.passwordCopied'),
    description: t('superAdmin.newUser.messages.passwordCopiedDescription', { password: form.state.password }),
    color: 'success'
  })
}

const uploadAvatar = async () => {
  try {
    if (!selectedFile.value) return ''
    const formData = new FormData()
    formData.append('image', selectedFile.value)
    const apiCall = useApiCall()
    const response = await apiCall('/api/upload-image', {
      method: 'POST',
      body: formData
    }) as { url: string }
    return response.url
  } catch {
    throw new Error(t('superAdmin.newUser.messages.uploadError'))
  }
}

const handleFileSelected = (file: File | null) => {
  selectedFile.value = file
  if (!file) {
    form.setField('avatarUrl', '')
  }
}
</script>
