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

const schema = z.object({
  user: z.string(),
  message: z.string().min(1, 'Message is required'),
  meta: z.object({
    browser: z.string(),
    screenResolution: z.string(),
    language: z.string(),
    platform: z.string(),
    colorScheme: z.string(),
    timezone: z.string(),
    url: z.string()
  })
})

const { user } = useAuth()
const log = useLogger('Feedback')
type Schema = z.output<typeof schema>

// Use form composable for consistent form handling
const form = useForm(schema, {
  user: user.value?.id,
  message: '',
  meta: {
    browser: navigator.userAgent,
    screenResolution: `${window.innerWidth}x${window.innerHeight}`,
    language: navigator.language,
    platform: navigator.platform,
    colorScheme: useColorMode().preference,
    timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
    url: `${window.location.origin}${window.location.pathname}`
  }
})

const emit = defineEmits<(e: 'close') => void>()
const toast = useToast()

async function onSubmit(event: FormSubmitEvent<Schema>) {
  await form.handleFormSubmit(
    event,
    async (data: Schema) => {
      const apiCall = useApiCall()
      await apiCall('/api/super-admin/feedback', {
        method: 'POST',
        body: data
      })
      toast.add({
        title: 'Your feedback has been submitted.',
        description: 'We will get back to you as soon as possible.',
        color: 'success'
      })
      emit('close')
    },
    {
      onError: (error: unknown) => {
        log.error('Failed to submit feedback:', error)
        toast.add({
          title: 'Error',
          description: 'Something went wrong. Please try again.',
          color: 'error'
        })
      }
    }
  )
}
</script>

<template>
  <UForm
    :schema="schema"
    :state="form.state"
    class="space-y-4"
    @submit="onSubmit"
  >
    <UFormField
      label="Message"
      name="message"
    >
      <UTextarea
        v-model="form.state.message"
        size="lg"
        variant="soft"
        class="w-full"
      />
    </UFormField>

    <UButton
      type="submit"
      size="lg"
      block
      :loading="form.isSubmitting.value"
      label="Submit"
    />
  </UForm>
</template>
