"use client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { InputOTP, InputOTPSlot } from "@/components/ui/input-otp";
import { useToast } from "@/components/ui/use-toast";
import useCountDown from "@/hooks/useCountDown";
import Axios from "@/lib/Axios";
import { yupResolver } from "@hookform/resolvers/yup";
import { useMutation } from "@tanstack/react-query";
import Image from "next/image";
import { useForm } from "react-hook-form";
import { EmailSchemaT, OtpSchemaT, emailSchema, otpSchema } from "../_schema";
import { useEffect } from "react";
import { AxiosError, AxiosResponse } from "axios";
import { RespError, UserDataT, UserT } from "@/types/auth";
import { useRouter, usePathname } from "next/navigation"; // Added usePathname
import useUserStore from "@/store/useUserStore";
import { setUserAuthData } from "@/actions/cookies";
import { Dispatch, SetStateAction, useState } from "react";
import "./style.scss";
import { returnErrorMessage } from "@/lib/utils";

let email = "";
const Page = () => {
  const { timer, startCountdown, tracker, completed, setCountDownValue } =
    useCountDown();

  const router = useRouter();
  const pathname = usePathname(); // Added usePathname to get current pathname

  const {
    register,
    handleSubmit,
    setValue,
    formState: { errors, isSubmitting },
  } = useForm<OtpSchemaT>({
    resolver: yupResolver(otpSchema),
  });

  const { toast } = useToast();
  const { setUserData } = useUserStore();
  const [loginToggler, setLoginToggler] = useState(false);
  const data = useUserStore((state) => state.data); // Changed to use data instead of isAuthenticated

  useEffect(() => {
    // Skip redirect if already on the login page
    if (pathname === "/login") return;

    if (!data) { // Check if data is undefined to determine authentication status
      router.push("/login");
    }
  }, [data, pathname, router]); // Updated dependencies

  const mutation = useMutation<
    AxiosResponse<UserT>,
    AxiosError<RespError>,
    any
  >({
    mutationFn: makeLogin,
    onError: (error, variables, context) => {
      const errorObj: Record<any, string[] | string> =
        error.response?.data.data!;
      const msg = returnErrorMessage(errorObj);
      toast({
        variant: "destructive",
        title: "Error",
        description: msg,
      });
    },
    onSuccess: async (data, variables, context) => {
      await setUserAuthData(data.data.data);
      setUserData(data.data.data);
      router.push("/customer");
    },
  });

  function makeLogin(data: EmailSchemaT) {
    return Axios.post("/core/login/", data);
  }

  function onSubmit(data: any) {
    mutation.mutate({ ...data, email });
  }

  return (
    <div className="login">
      <div className="login__logo">
        <div className="login__logo__logo-cont">
          <Image
            className="login__logo__logo-cont__logo-img"
            layout="fill"
            objectFit="cover"
            src="/assets/images/logo.png"
            alt="logo"
          />
        </div>
      </div>
      <div className="login__container">
        <p className="login__container__header">Welcome Back!</p>
        <p className="login__container__sub-header">
          Please Log In to your account
        </p>

        <GetOtp
          setCountDownValue={setCountDownValue}
          startCountdown={startCountdown}
          tracker={tracker}
          setLoginToggler={setLoginToggler}
        />

        {loginToggler && (
          <form
            onSubmit={handleSubmit(onSubmit)}
            className="login__container__form"
          >
            <p className="login__container__form__otp-info">
              A 5 digit OTP was sent to your E-mail ID
            </p>
            <div className="login__container__form__otp-cont">
              <InputOTP
                className="login__container__form__otp-cont__otp-group"
                onComplete={(otp) => {
                  setValue("otp", otp);
                }}
                maxLength={5}
              >
                <InputOTPSlot
                  className="login__container__form__otp-cont__otp-group__otp-slot"
                  index={0}
                />
                <InputOTPSlot
                  className="login__container__form__otp-cont__otp-group__otp-slot"
                  index={1}
                />
                <InputOTPSlot
                  className="login__container__form__otp-cont__otp-group__otp-slot"
                  index={2}
                />
                <InputOTPSlot
                  className="login__container__form__otp-cont__otp-group__otp-slot"
                  index={3}
                />
                <InputOTPSlot
                  className="login__container__form__otp-cont__otp-group__otp-slot"
                  index={4}
                />
              </InputOTP>
              <p className="login__container__form__otp-cont__error-msg">
                {errors

.otp?.message}
              </p>
            </div>

            {tracker && (
              <p className="login_ _container__form__countdown-cont">
                <span className="login__container__form__countdown-cont__number">
                  {`${Number(timer.minutes)}:${Number(timer.seconds)} `}
                </span>
                to resend the code
              </p>
            )}

            <Button
              type="submit"
              className="login__container__form__submit-btn bg-brownish hover:bg-brownish/40"
            >
              Login
            </Button>
          </form>
        )}
      </div>
    </div>
  );
};

type GetOtpT = {
  tracker: boolean;
  setCountDownValue: (num: number) => void;
  startCountdown: () => void;
  setLoginToggler: Dispatch<SetStateAction<boolean>>;
};

function GetOtp({
  setCountDownValue,
  startCountdown,
  tracker,
  setLoginToggler,
}: GetOtpT) {
  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
  } = useForm<EmailSchemaT>({
    resolver: yupResolver(emailSchema),
  });

  const { toast } = useToast();

  const mutation = useMutation({
    mutationFn: getOtp,
    onError: (error, variables, context) => {
      console.log(error.message, error.stack, error.name);
      toast({
        variant: "destructive",
        title: "Error",
        description: "Please check your net connection or Try again later",
      });
    },
    onSuccess: (data, variables, context) => {
      setCountDownValue(30);
      startCountdown();
      setLoginToggler(true);
      email = variables.email;
      toast({
        variant: "default",
        title: "Success",
        description: data?.data?.message,
      });
    },
  });

  async function getOtp(data: EmailSchemaT) {
    return Axios.post("/core/generate_otp/", data);
  }

  function onSubmit(data: EmailSchemaT) {
    if (tracker === false && mutation.isPending === false)
      mutation.mutate(data);
  }

  return (
    <form
      onSubmit={handleSubmit(onSubmit)}
      className="login__container__otp-form"
    >
      <div className="login__container__otp-form__container">
        <Input
          placeholder="E-mail ID"
          {...register("email")}
          className="login__container__otp-form__container__input"
        />
        <Button
          type="submit"
          variant="default"
          size="sm"
          className={`${
            tracker || mutation.isPending
              ? "login__container__otp-form__container__submit-btn__not-allow"
              : "login__container__otp-form__container__submit-btn"
          }`}
        >
          GET OTP
        </Button>
      </div>
      <p className="login__container__otp-form__email-error-msg">
        {errors.email?.message}
      </p>
    </form>
  );
}

export default Page;