import { useStateMachine } from "little-state-machine";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import Button from "../../../../../../shared/components/Button";
import Input from "../../../../../../shared/components/Input";
import Link from "../../../../../../shared/components/Link";
import { StepProps } from "../../../../components/Steps/Steps";

export type UserInfoFormValues = {
  email: string;
};

const UserInfo: React.FC<StepProps> = ({ onStepCompleted }) => {
  const { state } = useStateMachine();

  const {
    handleSubmit,
    register,
    formState: { errors },
  } = useForm<UserInfoFormValues>({
    defaultValues: state.userInfo,
  });

  const onSubmit = (data: UserInfoFormValues) => {
    onStepCompleted({ userInfo: data });
  };

  const { t } = useTranslation();

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Input
        type="email"
        placeholder={t("e.g. John@email.com")}
        autoComplete="email"
        label={t("E-mail")}
        required
        error={errors.email}
        {...register("email", {
          required: {
            value: true,
            message: t("Required field"),
          },
          pattern: {
            value: /\S+@\S+.\S+/,
            message: t("Invalid email"),
          },
        })}
      />
      <Button type="submit" className="mt-10">
        {t("Next")}
      </Button>
      <Link className="pl-5" href="http://watch.ohjazz.tv/login">
        {t("Already a member")}
      </Link>
    </form>
  );
};

export default UserInfo;
