"use client";

import React, { useState, useEffect } from "react";
import { Formik, Field, Form } from "formik";
import * as Yup from "yup";
import { useDispatch } from "react-redux";
import { resetPassword } from "../../../api/api";
import { AppDispatch } from "../../../store";
import eye from "../../../assets/eye.svg";
import closedeye from "../../../assets/closedeye.png";
import OTPInput from "react-otp-input";
import Image from "next/image";
import { toast } from "react-toastify";
import { useRouter } from "next/navigation";

const ResetPassword: React.FC = () => {
  const router = useRouter();
  const dispatch: AppDispatch = useDispatch();
  const [showPassword, setShowPassword] = useState(false);
  const [password, setPassword] = useState("");
  // const [confirmError, setConfirmError] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [email, setEmail] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [requirements, setRequirements] = useState({
    length: false,
    uppercase: false,
    lowercase: false,
    number: false,
    specialChar: false,
  });
  const [otp, setOtp] = useState("");
  const [otpError, setOtpError] = useState<string | null>(null);

  useEffect(() => {
    const routesToPrefetch = ["/"];

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

  useEffect(() => {
    const queryParams = new URLSearchParams(window.location.search);
    const encodedEmail = queryParams.get("email");
    if (encodedEmail) {
      const decodedEmail = atob(encodedEmail);
      setEmail(decodedEmail);
    }
  }, []); // Run only once on mount

  const handleChangePwd = (e: React.ChangeEvent<HTMLInputElement>) => {
    setPassword(e.target.value);
    setRequirements({
      length: e.target.value.length >= 8,
      uppercase: /[A-Z]/.test(e.target.value),
      lowercase: /[a-z]/.test(e.target.value),
      number: /[0-9]/.test(e.target.value),
      specialChar: /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/.test(e.target.value),
    });
  };

  const isAllRequirementsMet = () => {
    return (
      requirements.length &&
      requirements.uppercase &&
      requirements.lowercase &&
      requirements.number &&
      requirements.specialChar
    );
  };

  const handleConfirmPwdChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setConfirmPassword(e.target.value);
    // if (e.target.value !== password) {
    //   setConfirmError("Passwords must match");
    // } else {
    //   setConfirmError("");
    // }
  };

  // const isEmptyObject = (obj: any) => {
  //   return Object.keys(obj).length === 0;
  // };

  const handleChange = (otp: string, setFieldValue: any) => {
    setOtp(otp);
    setFieldValue("otp", otp);
    setOtpError(null);
  };

  return (
    <div className="max-w-md mx-auto bg-white mt-10 rounded-xl p-8 px-10 mb-10">
      <h1 className="text-3xl font-bold mb-4 text-[#1E1E1E]">Reset Password</h1>
      <p className="text-sm font-semibold text-center mb-10 text-[#1E1E1E]">
        Please enter your new password below.
      </p>
      <Formik
        initialValues={{
          password: "",
          confirmPassword: "",
          otp: "",
        }}
        validationSchema={Yup.object({
          password: Yup.string()
            .min(8, "Password must be at least 8 characters")
            .required("Password is required"),
          confirmPassword: Yup.string()
            .nullable()
            .required("Confirm Password is required"),
          otp: Yup.string()
            .length(4, "OTP must be exactly 4 digits")
            .required("OTP is required"),
        })}
        onSubmit={async (values: any) => {
          setIsLoading(true);
          setOtpError(null);
          values.email = email;

          try {
            const result = await dispatch(resetPassword(values)).unwrap();
            console.log("success--------", result);
            // ✅ API was successful
            toast.success(
              result?.data?.message || "Password reset successfully!"
            );
            router.push("/");
          } catch (error: any) {
            // ❌ API failed, you get clean string error from `rejectWithValue`
            console.log("Error:", error);
            setOtpError(error);
            toast.error(error);
          } finally {
            setIsLoading(false);
          }
        }}
      >
        {(formikProps) => {
          const { setFieldValue, errors, touched } = formikProps;
          return (
            <Form className="space-y-4">
              <div className="relative text-[#1E1E1E]">
                <Field
                  type={showPassword ? "text" : "password"}
                  id="password"
                  name="password"
                  className={`block w-full border ${
                    formikProps.errors.password &&
                    formikProps.touched.password &&
                    !isAllRequirementsMet()
                      ? "border-red-500"
                      : "border-gray-300"
                  } rounded-md p-2 form-input`}
                  placeholder="Password"
                  value={password}
                  onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
                    formikProps.handleChange(e);
                    handleChangePwd(e);
                  }}
                />
                <Image
                  unoptimized
                  src={showPassword ? closedeye : eye}
                  alt="Toggle password visibility"
                  className={`cursor-pointer absolute w-4 right-[2%] ${
                    showPassword ? "top-[14px]" : "top-[16px]"
                  }`}
                  width={16}
                  height={16}
                  onClick={() => setShowPassword(!showPassword)}
                />
                {formikProps.touched.password &&
                  typeof formikProps.errors.password === "string" && (
                    <div className="text-red-500 mt-1 text-start text-sm">
                      {formikProps.errors.password}
                    </div>
                  )}
              </div>
              <div className="flex flex-wrap gap-x-4 gap-y-2 font-semibold text-sm ">
                <div className="flex items-center min-w-[142px] gap-1 text-black ">
                  <input
                    type="checkbox"
                    checked={requirements.length}
                    disabled
                    className="h-4 w-4 rounded border-gray-400 text-black "
                  />{" "}
                  8 Characters
                </div>
                <div className="flex items-center min-w-[142px] gap-1 text-black">
                  <input
                    type="checkbox"
                    checked={requirements.lowercase}
                    disabled
                    className="h-4 w-4 rounded border-gray-400 text-black "
                  />{" "}
                  Lowercase
                </div>
                <div className="flex items-center min-w-[142px] gap-1 text-black">
                  <input
                    type="checkbox"
                    checked={requirements.specialChar}
                    disabled
                    className="h-4 w-4 rounded border-gray-400 text-black "
                  />{" "}
                  Special Character
                </div>
                <div className="flex items-center min-w-[142px] gap-1 text-black">
                  <input
                    type="checkbox"
                    checked={requirements.uppercase}
                    disabled
                    className="h-4 w-4 rounded border-gray-400 text-black "
                  />{" "}
                  Uppercase
                </div>
                <div className="flex items-center min-w-[142px] gap-1 text-black">
                  <input
                    type="checkbox"
                    checked={requirements.number}
                    disabled
                    className="h-4 w-4 rounded border-gray-400 text-black "
                  />{" "}
                  Number
                </div>
              </div>
              <div>
                <Field
                  type="password"
                  id="confirmPassword"
                  name="confirmPassword"
                  className={`block w-full border ${
                    formikProps.errors.confirmPassword &&
                    formikProps.touched.confirmPassword
                      ? "border-red-500"
                      : "border-gray-300"
                  } rounded-md p-2 form-input`}
                  placeholder="Confirm Password"
                  onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
                    formikProps.handleChange(e);
                    handleConfirmPwdChange(e);
                  }}
                  value={confirmPassword}
                />
                {formikProps.touched.confirmPassword &&
                  typeof formikProps.errors.confirmPassword === "string" && (
                    <div className="text-red-500 mt-1 text-start text-sm">
                      {formikProps.errors.confirmPassword}
                    </div>
                  )}
              </div>
              <div>
                <p className="font-semibold mt-5 mb-1 text-black">
                  Enter OTP sent on your email/phone
                </p>
                {/* <OTPInput
                  value={otp}
                  onChange={(otp: string) => handleChange(otp, setFieldValue)}
                  numInputs={4}
                  renderInput={(inputProps) => <input {...inputProps} />}
                  containerStyle={{ justifyContent: "space-evenly" }}
                  inputStyle={{ borderRadius: "5px", width: "40px" }}
                /> */}
                <OTPInput
                  value={otp}
                  onChange={(otp: string) => handleChange(otp, setFieldValue)}
                  numInputs={4}
                  containerStyle={{ justifyContent: "space-evenly" }}
                  inputStyle={{
                    borderRadius: "5px",
                    width: "40px",
                    height: "40px", // Add height for consistency
                    fontSize: "16px",
                    border: "1px solid #ccc",
                  }}
                  focusStyle={{
                    border: "1px solid #3b82f6",
                    outline: "none",
                  }}
                />
                {touched.otp && errors.otp ? (
                  <div style={{ color: "red" }} className="text-center">
                    {String(errors.otp)}
                  </div>
                ) : null}
                {otpError && (
                  <div style={{ color: "red" }} className="text-center">
                    {otpError}
                  </div>
                )}
              </div>
              <div>
                <button
                  type="submit"
                  className="custom-button w-full text-black"
                  // disabled={
                  //   !isEmptyObject(formikProps.errors) ||
                  //   confirmError !== "" ||
                  //   !isAllRequirementsMet()
                  // }
                >
                  {isLoading ? <span className="loader"></span> : "Save"}
                  {/* Save */}
                </button>
              </div>
            </Form>
          );
        }}
      </Formik>
    </div>
  );
};

export default ResetPassword;
