"use client";

import React, { useEffect, useState } from "react";
import { Formik, Field, Form } from "formik";
import * as Yup from "yup";
import { useRouter, useSearchParams } from "next/navigation";
import Image from "next/image";
import { useDispatch } from "react-redux";
import { toast } from "react-toastify";
import Cookies from "js-cookie";

import eye from "../../../assets/eye.svg";
import closedeye from "../../../assets/closedeye.png";

import {
  sellerLogin,
  cashWalletHistory,
  getsIncrement,
} from "../../../api/api";
import { setToken } from "../../../slice/TokenSlice";
import { setUserLetter } from "../../../slice/ImageSlice";
import { AppDispatch } from "../../../store";

const LoginForm: React.FC = () => {
  const router = useRouter();
  const dispatch: AppDispatch = useDispatch();
  const searchParams = useSearchParams();
  const [showPassword, setShowPassword] = useState(false);
  const redirect = searchParams.get("callbackUrl") || "/";
  useEffect(() => {
    const routesToPrefetch = ["/auth/register", "/auth/forgot-password"];

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

  return (
    <div className="max-w-md mx-auto bg-white mt-10 rounded-xl p-8 px-10 mb-10 text-navy">
      <h1 className="text-3xl font-bold mb-4 text-center">Login</h1>
      <p className="text-sm font-semibold text-center mb-10">
        Log in using your registered account
      </p>

      <Formik
        initialValues={{ email: "", password: "" }}
        validationSchema={Yup.object({
          email: Yup.string()
            .trim()
            .email("Invalid email address")
            .matches(
              /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
              "Invalid email address"
            )
            .required("Email is required"),
          password: Yup.string().required("Password is required"),
        })}
        onSubmit={(values) => {
          localStorage.setItem("password", values.password);

          dispatch(sellerLogin(values)).then((response: any) => {
            if (response.payload.status_code === 200) {
              const token = response.payload.data.token;

              dispatch(setToken(token));
              Cookies.set("token", token, { expires: 1 });

              const userLetter = response.payload.data.user.email
                .trim()
                .charAt(0)
                .toUpperCase();
              dispatch(setUserLetter(userLetter));

              toast.success("Logged in successfully");

              router.push(redirect);

              setTimeout(() => {
                dispatch(cashWalletHistory());
                dispatch(getsIncrement());
              }, 1000);
            } else if (response.payload.error) {
              toast.error(response.payload.error);
            }
          });
        }}
      >
        {(formikProps) => (
          <Form className="space-y-4">
            <div>
              <Field
                type="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"
              />
              {formikProps.errors.email && formikProps.touched.email && (
                <span className="text-red-500 text-xs mt-1 block">
                  {formikProps.errors.email}
                </span>
              )}
            </div>

            <div className="relative">
              <Field
                type={showPassword ? "text" : "password"}
                name="password"
                className={`block w-full ${
                  formikProps.errors.password && formikProps.touched.password
                    ? "border-red-500"
                    : "border-gray-300"
                } rounded-md p-2 form-input text-black`}
                placeholder="Password"
              />
              <Image
                unoptimized
                src={showPassword ? closedeye : eye}
                alt="Toggle password visibility"
                width={20}
                height={20}
                className={`cursor-pointer absolute right-[2%] ${
                  showPassword ? "top-[11px]" : "top-[14px]"
                }`}
                onClick={() => setShowPassword(!showPassword)}
              />
              {formikProps.errors.password && formikProps.touched.password && (
                <span className="text-red-500 text-xs mt-1 block">
                  {formikProps.errors.password}
                </span>
              )}
            </div>

            <p
              className="text-end text-sm font-semibold cursor-pointer"
              onClick={() => router.push("/auth/forgot-password")}
            >
              Forgotten password?
            </p>

            <div>
              <button
                type="submit"
                className="text-[#1E1E1E] py-2 px-4 rounded-md w-full bg-[#F8CB1F] transition ease-in-out hover:-translate-y-1 hover:scale-110"
              >
                Login
              </button>
            </div>

            <p className="text-center text-sm font-semibold">
              Don't have an account?{" "}
              <span
                className="text-blue-600 cursor-pointer"
                onClick={() => router.push("/auth/register")}
              >
                Register here
              </span>
            </p>
          </Form>
        )}
      </Formik>
    </div>
  );
};

export default LoginForm;
