import { TextInput } from "@mantine/core";
import { useForm } from "@mantine/form";
import { Trans, useLingui } from "@lingui/react/macro";
import useCreateUser from "../hooks/use-create-user";
import Button from "@/components/button";

const NamePrompt = () => {
  const { t } = useLingui();
  const form = useForm({
    initialValues: {
      first_name: '',
      last_name: ''
    },
    validate: {
      first_name: (value) => {
        if (value.length === 0) return t`First name is required`
        if (!(/^[a-zA-Z\s]{3,20}$/).test(value)) return t`First name must be 3-20 characters long and contain only letters`
      },
      last_name: (value) => {
        if (value.length === 0) return t`Last name is required`
        if (!(/^[a-zA-Z\s]{3,20}$/).test(value)) return t`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={t`First Name`}
        key={form.key('first_name')}
        {...form.getInputProps('first_name')}
      />
      <TextInput
        id="last_name"
        label={t`Last Name`}
        key={form.key('last_name')}
        {...form.getInputProps('last_name')}
      />
      <Button loading={isPending} type='submit' mt='10px' variant='filled'><Trans>Create Account</Trans></Button>
    </form>
  )
}

export default NamePrompt;
