File size: 1,796 Bytes
241884b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm, SubmitHandler } from "react-hook-form";
import { z } from "zod";
import { Input } from "./ui/input";
import { Button } from "./ui/button";
import { Label } from "./ui/label";
import { sendResetEmail } from "@/utils/forgotPassword";
import { useState } from "react";

const schema = z.object({
  email: z.string().email("Email tidak valid"),
});

type FormFields = z.infer<typeof schema>;

export default function ForgotPasswordForm() {
  const [successMsg, setSuccessMsg] = useState<string | null>(null);
  const {
    register,
    handleSubmit,
    setError,
    formState: { errors, isSubmitting },
  } = useForm<FormFields>({ resolver: zodResolver(schema) });

  const onSubmit: SubmitHandler<FormFields> = async ({ email }) => {
    setSuccessMsg(null);
    const res = await sendResetEmail(email);
    if (!res.ok) {
      setError("root", { message: res.message });
      return;
    }
    setSuccessMsg(res.message);
  };

  return (
    <form className="flex flex-col gap-2" onSubmit={handleSubmit(onSubmit)}>
      <Label htmlFor="email" className="text-left">
        Email
      </Label>
      <Input id="email" type="email" placeholder="Email" {...register("email")} />
      {errors.email && (
        <div className="text-left text-xs text-red-500">{errors.email.message}</div>
      )}
      <Button disabled={isSubmitting} type="submit" className="mt-4 bg-orange-600 hover:bg-orange-800">
        {isSubmitting ? "Mengirim..." : "Kirim tautan reset"}
      </Button>
      {errors.root && (
        <div className="text-xs text-red-500">{errors.root.message}</div>
      )}
      {successMsg && (
        <div className="text-xs text-green-600">{successMsg}</div>
      )}
    </form>
  );
}