"use client";
import postData from "@/api/post-data";
import CustomBreadcrumb from "@/app/ui/shared/CustomBreadcrumb";
import CustomPhoneInput from "@/app/ui/shared/CustomPhoneInput";
import SubmitButton from "@/app/ui/shared/SubmitButton";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { toastError, toastSuccess } from "@/services/custom-toast";
import { zodResolver } from "@hookform/resolvers/zod";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { z } from "zod";

export default function ForgotPassword() {
  const t = useTranslations("forgot-password");
  const label = useTranslations("form-labels");
  const error = useTranslations("form-errors");
  const router = useRouter();
  const form = useForm({
    resolver: zodResolver(
      z.object({
        phone: z
          .string({ errorMap: () => ({ message: error("email") }) })
          .min(9, error("mobile")),
      })
    ),
  });
  const {
    formState: { isSubmitting },
  } = form;
  async function onSubmit(data) {
    const formData = new FormData();
    formData.append("phone", data?.phone?.replace("+", ""));
    const {
      error,
      message,
      data: res,
    } = await postData({
      endPoint: "/reset/check_email",
      body: formData,
    });
 
    if (error) {
      toastError(message);
      return;
    }
    router.push(`/forgot-password/verify-code/${data.phone.replace("+", "")}`);
    toastSuccess(message);
  }
  return (
    <>
      <CustomBreadcrumb />
      <section className="max-md:mx-4 mt-12 mb-20 rounded-lg p-4 md:p-8 shadow-lg md:w-1/2 mx-auto">
        <div className="mb-12">
          <h1 className="font-bold text-xl text-center md:text-2xl lg:text-3xl text-dark mb-12">
            {t("title")}
          </h1>
        </div>
        <Form {...form}>
          <form
            method="post"
            onSubmit={form.handleSubmit(onSubmit)}
            className="space-y-6"
          >
            <FormField
              name="phone"
              control={form.control}
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <CustomPhoneInput
                      value={field.value}
                      valueOnChange={field.onChange}
                      placeholder={label("mobile")}
                      className={"flex gap-2"}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Submit button */}
            <SubmitButton text={t("continue")} loading={isSubmitting} />
          </form>
        </Form>
      </section>
    </>
  );
}
