"use client";

import React, { useEffect, useState } from "react";
import { Formik, Field, Form } from "formik";
import * as Yup from "yup";
import { AppDispatch } from "../../../store";
import { useDispatch } from "react-redux";
import { forgotPassword } from "../../../api/api";
import load from "../../../assets/loading.gif";
import { toast } from "react-toastify";
import Image from "next/image";
import { useRouter } from "next/navigation";

const ForgotPassword: React.FC = () => {
  const dispatch: AppDispatch = useDispatch();
  const [loading, setLoading] = useState(false);
  const router = useRouter();

  useEffect(() => {
    const routesToPrefetch = ["/auth/email-sent"];

    routesToPrefetch.forEach((route) => {
      router.prefetch(route);
    });
  }, [router]);

  return (
    <div className="flex justify-center">
      <div className="max-w-md mx-auto bg-white mt-10 rounded-xl md:p-8 px-10 mb-10 xs:m-3 md:m-10 ">
        <h1 className="text-3xl font-bold mb-4 text-[#1E1E1E] text-center xs:pt-3">
          Forgot Password
        </h1>
        <p className="text-sm font-semibold text-center mb-10 text-[#1E1E1E]">
          Please enter your email address below and we will send you an email to
          change your password.
        </p>
        <Formik
          initialValues={{
            email: "",
          }}
          validationSchema={Yup.object({
            email: Yup.string()
              .email("Invalid email address")
              .required("Email is required"),
          })}
          onSubmit={(values: any) => {
            console.log("v", values);
            setLoading(true);
            // setErrorMessage(null); // Reset any previous error message

            dispatch(forgotPassword(values.email))
              .then((response: any) => {
                console.log("response", response);
                localStorage.setItem("email", values.email);
                if (response?.payload?.status_code === 200) {
                  setLoading(false);
                  router.push("/auth/email-sent");
                } else {
                  setLoading(false);
                  toast.error(
                    response?.payload?.error || "Something went wrong"
                  );
                }
              })
              .catch(() => {
                setLoading(false);
                // setErrorMessage(
                //   "An error occurred while trying to send the reset email. Please try again later."
                // );
              });
          }}
        >
          {(formikProps) => (
            <Form className="">
              <div>
                <Field
                  type="email"
                  id="email"
                  name="email"
                  className={`block w-full ${
                    formikProps.errors.email && formikProps.touched.email
                      ? "border-red-500"
                      : "border-gray-300"
                  } rounded-md p-2 form-input text-black`}
                  placeholder="Email Address"
                />
              </div>
              {formikProps.touched.email &&
                typeof formikProps.errors.email === "string" && (
                  <div className="text-red-500 mt-1 text-start text-sm">
                    {formikProps.errors.email}
                  </div>
                )}
              <div>
                {!loading ? (
                  <button
                    type="submit"
                    className="text-black py-2 px-4 mt-4 rounded-md w-full bg-[#F8CB1F] transition ease-in-out hover:-translate-y-1 hover:scale-110"
                  >
                    Send Email
                  </button>
                ) : (
                  <Image
                    unoptimized
                    src={load?.src}
                    alt="Loading..."
                    className="m-auto mt-8"
                    height={36}
                    width={36}
                  />
                )}
              </div>
            </Form>
          )}
        </Formik>
      </div>
    </div>
  );
};

export default ForgotPassword;
