import { TextInput } from "@mantine/core";
import { useForm } from "@mantine/form";
import useCreateUser from "../hooks/use-create-user";
import Button from "@/components/button";

const NamePrompt = () => {  
  const form = useForm({
    initialValues: {
      first_name: '',
      last_name: ''
    },
    validate: {
      first_name: (value) => {
        if (value.length === 0) return 'First name is required'
        if (!(/^[a-zA-Z\s]{3,20}$/).test(value)) return 'First name must be 3-20 characters long and contain only letters'
      },
      last_name: (value) => {
        if (value.length === 0) return 'Last name is required'
        if (!(/^[a-zA-Z\s]{3,20}$/).test(value)) return 'Last name must be 3-20 characters long and contain only letters'
      }
    }
  })


  const { mutate: createUser, isPending } = useCreateUser();
  const handleSubmit = (data: { first_name: string, last_name: string }) => {
    form.reset();
    return createUser(data);
  }

  return (
    <form onSubmit={form.onSubmit(handleSubmit)}>
      <TextInput
        id="first_name"
        label='First Name'
        key={form.key('first_name')}
        {...form.getInputProps('first_name')}
      />
      <TextInput
        id="last_name"
        label='Last Name'
        key={form.key('last_name')}
        {...form.getInputProps('last_name')}
      />
      <Button loading={isPending} type='submit' mt='10px' variant='filled'>Create Account</Button>
    </form>
  )
}

export default NamePrompt;
