<script setup lang="ts">
import type { z } from 'zod'
import { toTypedSchema } from '@vee-validate/zod'
import { Loader2 } from 'lucide-vue-next'
import { useForm } from 'vee-validate'

interface Props {
  schema: z.ZodSchema<any>
  isLoading: boolean
}

const props = defineProps<Props>()

const emit = defineEmits<{
  submit: [data: any]
}>()

const { handleSubmit, defineField, errors, meta } = useForm({
  validationSchema: toTypedSchema(props.schema),
  initialValues: {
    name: '',
    password: '',
  },
})

const [name, nameAttrs] = defineField('name')
const [password, passwordAttrs] = defineField('password')

const onSubmit = handleSubmit(async (values) => {
  try {
    await emit('submit', values)
  } catch (error) {
    console.error('Submission failed:', error)
  }
})
</script>

<template>
  <form class="grid gap-6" @submit="onSubmit">
    <div class="grid gap-2">
      <Label for="name">Username</Label>
      <Input
        id="name"
        v-model="name"
        v-bind="nameAttrs"
        :disabled="isLoading"
        :class="{ 'border-red-500': errors.name }"
      />
      <span v-if="errors.name" class="text-sm text-red-500">
        {{ errors.name }}
      </span>
    </div>

    <div class="grid gap-2">
      <Label for="password">Password</Label>
      <Input
        id="password"
        v-model="password"
        v-bind="passwordAttrs"
        type="password"
        :disabled="isLoading"
        :class="{ 'border-red-500': errors.password }"
      />
      <span v-if="errors.password" class="text-sm text-red-500">
        {{ errors.password }}
      </span>
    </div>

    <Button type="submit" class="w-full" :disabled="isLoading || !meta.valid">
      <Loader2 v-if="isLoading" class="mr-2 h-4 w-4 animate-spin" />
      Login
    </Button>
  </form>
</template>
