"use client";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { useEffect, useState, useLayoutEffect, use } from "react";
import { signIn, useSession } from "next-auth/react";
import { redirect, useSearchParams } from "next/navigation";
import { useForm } from "react-hook-form";
import { toast, Flip } from "react-toastify";
import { zodResolver } from "@hookform/resolvers/zod";
import { loginSchema } from "@/lib/zodSchemas";
import checkPasswordStrength from "@/lib/strongPassCheck";
import { UserRole } from "@prisma/client";
import Image from "next/image";
import { useDispatch, useSelector } from "react-redux";
import { AppDispatch } from "@/redux/store";
import { mergeCartWithBackend } from "@/redux/slices/cartSlice";

const LoginForm = () => {
  const { data: session } = useSession();
  const [email, setEmail] = useState("");
  const searchParams = useSearchParams();

  const dispatch = useDispatch<AppDispatch>()
  const cart = useSelector((state: any) => state.cart)

  useEffect(() => {
    const error = searchParams.get("error");
    if (error === "hasCredentialsAccount") {
      toast.error(
        "You already have an account. Please login with your email and password.",
        {
          position: "bottom-right",
          autoClose: 4000,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
          theme: "colored",
          transition: Flip,
        }
      );
    }

    if (error === "unverifiedMail") {
      toast.error("Please verify your email before logging in.", {
        position: "bottom-right",
        autoClose: 4000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
        theme: "colored",
        transition: Flip,
      });
    }
  });

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(loginSchema),
  });

  const resetPassword = async (email: string) => {
    try {
      const response = await fetch("/api/mailConfirmation", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          email,
        }),
      });
      return await response.json();
    } catch (error: any) {
      // await logToServer("error", "Failed to reset password " + error.message)
      throw new Error("Failed to reset password." + error.message);
    }
  };

  const handleResetPassword = async (email: string) => {
    if (email === "") {
      toast.error("Please enter your email", {
        position: "bottom-right",
        autoClose: 4000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
        theme: "colored",
        transition: Flip,
      });
      return;
    }
    try {
      const response = await resetPassword(email);

      if (response.status === 404) {
        toast.warning(response.message, {
          position: "bottom-right",
          autoClose: 4000,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
          theme: "colored",
          transition: Flip,
        });
      } else {
        toast.success(response.message, {
          position: "bottom-right",
          autoClose: 4000,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
          theme: "colored",
          transition: Flip,
        });
      }
    } catch (error: any) {
      toast.error(error.message, {
        position: "bottom-right",
        autoClose: 4000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
        theme: "colored",
        transition: Flip,
      });
    }
  };

  const onSubmit = async (data: any) => {
    try {
      const passwordStrength = checkPasswordStrength(data.password);
      let passwordStrengthMessage = "";
      if (passwordStrength === 1) {
        passwordStrengthMessage = "Weak password";
      } else if (passwordStrength === 2) {
        passwordStrengthMessage = "Medium password";
      } else {
        passwordStrengthMessage = "Strong password";
      }

      const result = await signIn("credentials", {
        email: data.email,
        password: data.password,
        redirect: false,
        callbackUrl: "/login",
      });

      if (result?.error) {
        if (result.error === "unverifiedMail") {
          // await logToServer("error", `Please verify your email before logging in. ${data.email}`);
          toast.error("Please verify your email before logging in.", {
            position: "bottom-right",
            autoClose: 4000,
            hideProgressBar: false,
            closeOnClick: true,
            pauseOnHover: true,
            draggable: true,
            progress: undefined,
            theme: "colored",
            transition: Flip,
          });
        } else {
          // await logToServer("error", `Invalid credentials: ${data.email}`);
          toast.error("Invalid credentials", {
            position: "bottom-right",
            autoClose: 4000,
            hideProgressBar: false,
            closeOnClick: true,
            pauseOnHover: true,
            draggable: true,
            progress: undefined,
            theme: "colored",
            transition: Flip,
          });
        }
      } else {

        // Login successful
        // console.log('CART ITEMS', cart)
        // console.log(cart.items)
        dispatch(mergeCartWithBackend(cart.items))

        toast.success("Login successful!", {
          position: "bottom-right",
          autoClose: 4000,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
          theme: "colored",
          transition: Flip,
        });
      }
    } catch (error: any) {
      toast.warning("Please verify your email before logging in.", {
        position: "bottom-right",
        autoClose: 4000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
        theme: "colored",
        transition: Flip,
      });
    }
  };

  const handleEmailChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setEmail(e.target.value);
  };

  const handleSignIn = async () => {
    try {
      const response = await signIn("google", {
        redirect: false,
        callbackUrl: "/",
      });
      // dispatch(mergeCartWithBackend(cart.items))

    } catch (error: any) {
      // await logToServer("error", error.message);
      toast.error(error.message, {
        position: "bottom-right",
        autoClose: 4000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
        theme: "colored",
        transition: Flip,
      });
    }
  };

  useLayoutEffect(() => {
    if (session) {
      if (session.user.role === UserRole.ADMIN) {
        redirect("/admin/dashboard");
      } else {
        redirect("/");
      }
    }
  }, [session]);

  return (
    <div className="flex flex-col gap-0">
      <Card className="bg-white">
        <CardHeader className="text-center">
          <CardTitle className="text-xl">Welcome back to Barrack</CardTitle>
          <CardDescription>
            Login with your Email or Google account
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit(onSubmit)}>
            <div className="grid gap-6">
              <div className="grid gap-6">
                <div className="grid gap-2">
                  <Label htmlFor="email">Email</Label>
                  <Input
                    id="email"
                    type="email"
                    placeholder="m@example.com"
                    required
                    {...register("email")}
                    onChange={handleEmailChange}
                  />
                  {errors.email && typeof errors.email.message === "string" && (
                    <div className="text-red-500">{errors.email.message}</div>
                  )}
                </div>
                <div className="grid gap-2">
                  <div className="flex items-center">
                    <Label htmlFor="password">Password</Label>
                    <a
                      href="/resetPassword"
                      className="ml-auto text-sm underline-offset-4 hover:underline"
                      onClick={(e) => {
                        e.preventDefault();
                        handleResetPassword(email);
                      }}
                    >
                      Forgot your password?
                    </a>
                  </div>
                  <Input
                    id="password"
                    type="password"
                    required
                    {...register("password")}
                  />
                  {errors.password &&
                    typeof errors.password.message === "string" && (
                      <div className="text-red-500">
                        {errors.password.message}
                      </div>
                    )}
                </div>
                <Button
                  type="submit"
                  className="w-full text-white bg-primary hover:bg-secondary"
                >
                  Login
                </Button>
              </div>
              <div className="relative text-center text-sm after:absolute after:inset-0 after:top-1/2 after:z-0 after:flex after:items-center after:border-t after:border-border">
                <span className="relative z-10 bg-white px-2 text-muted-foreground">
                  Or continue with
                </span>
              </div>
              <div className="flex flex-col gap-4">
                <Button
                  type="button"
                  variant="outline"
                  className="w-full"
                  onClick={handleSignIn}
                >
                  <Image
                    src="/logo/google.svg"
                    alt="Google logo"
                    width={24}
                    height={24}
                    className="mr-2"
                  />
                  Login with Google
                </Button>
              </div>
              <div className="text-center text-sm">
                Don&apos;t have an account?{" "}
                <a href="/signup" className="underline underline-offset-4">
                  Sign up
                </a>
              </div>
            </div>
          </form>
        </CardContent>
      </Card>
      <div className="text-balance text-center text-xs text-muted-foreground [&_a]:underline [&_a]:underline-offset-4 [&_a]:hover:text-primary mt-4">
        By continuing, you agree to our <a href="/privacy">Terms of Service</a> and{" "}
        <a href="/privacy">Privacy Policy</a>.
      </div>
    </div>
  );
};

export default LoginForm
