"use client";
import Link from "next/link";
import Image from "next/image";
import google from "@/components/admin/assets/google.png";
import * as React from "react";
import { useEffect, useState } from "react";
import { EyeOff, Eye, Store } from "lucide-react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
  CardFooter,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { toast, Flip } from "react-toastify";
import checkPasswordStrength from "@/lib/strongPassCheck";
import { loginSchema } from "@/lib/zodSchemas";
import { signIn, useSession } from "next-auth/react";
import { useLayoutEffect } from "react";
import { redirect, useSearchParams } from "next/navigation";
import {UserRole} from "@prisma/client";
// import { logToServer } from "@/utils/logger-client";

const LoginForm = () => {
  const { data: session } = useSession();
  const [passwordVisible, setPasswordVisible] = useState(false);
  const [email, setEmail] = useState("");
  const searchParams = useSearchParams();

  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 {
        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: "/",
      });
    } 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 (
    <>
      {/* old code */}
      <section>
        <Card className="mx-auto max-w-md max-sm:max-w-[350px] bg-blue-2 p-4 shadow-lg shadow-black/30 py-12 mt-10 mb-10">
          <CardHeader>
            <CardTitle className="text-heading4-bold mx-auto mb-8">
              <p>
                Login to <span className="text-blue-1 uppercase">Barrack</span>{" "}
              </p>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit(onSubmit)}>
              <div className="grid gap-4">
                <div className="grid gap-2 text-black">
                  <Label htmlFor="email">Enter Email</Label>
                  <Input
                    id="email"
                    type="email"
                    placeholder="example@mail.com"
                    {...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 text-black">
                    <Label htmlFor="password">Password</Label>
                    <Link
                      href="/resetPassword"
                      className="ml-auto inline-block text-sm underline"
                      onClick={(e) => {
                        e.preventDefault();
                        handleResetPassword(email);
                      }}
                    >
                      Forgot your password?
                    </Link>
                  </div>
                  <div className="relative select-none">
                    <Input
                      id="password"
                      type={passwordVisible ? "text" : "password"}
                      {...register("password")}
                      className="pr-8"
                      aria-label="Toggle password visibility"
                    />
                    {passwordVisible ? (
                      <Eye
                        className="absolute top-1/2 right-5 transform translate-x-1/2 -translate-y-1/2 w-5 cursor-pointer"
                        onClick={() => setPasswordVisible(!passwordVisible)}
                      />
                    ) : (
                      <EyeOff
                        className="absolute top-1/2 right-6 transform translate-x-1/2 -translate-y-1/2 w-5 cursor-pointer"
                        onClick={() => setPasswordVisible(!passwordVisible)}
                      />
                    )}
                  </div>
                  {errors.password &&
                    typeof errors.password.message === "string" && (
                      <div className="text-red-500">
                        {errors.password.message}
                      </div>
                    )}
                </div>
                <Button type="submit" className="w-full bg-black text-white">
                  Login
                </Button>
              </div>
            </form>
            <Button
              variant="outline"
              className="border-grey-1 mt-4  w-full"
              onClick={handleSignIn}
            >
              <Image
                src={google}
                width={18}
                height={18}
                alt="google"
                className="mr-2"
              />
              Google এর মাধ্যম সাইন-ইন করুন
            </Button>
            <div className="mt-4 text-center text-sm">
              Don&apos;t have an account?{" "}
              <Link href="/login/signup" className="underline">
                Sign up
              </Link>
            </div>
          </CardContent>
        </Card>
      </section>

      {/* new code */}
      {/* <section>
        <div className=" min-h-screen flex items-center justify-center bg-gray-100 py-12 px-4 sm:px-6 lg:px-8">
          <Card className="max-w-md w-full bg-white shadow-lg">
            <CardHeader className="text-center space-y-2">
              <Link
                href="/"
                className="flex items-center justify-center space-x-2 text-darkBlue"
              >
                <Store className="h-8 w-8" />
                <span className="text-2xl font-bold">Barrack</span>
              </Link>
              <CardTitle className="text-3xl font-extrabold">
                Welcome back
              </CardTitle>
              <CardDescription>Please sign in to your account</CardDescription>
            </CardHeader>

            <CardContent>
              <form className="space-y-4">
                <div className="space-y-4">
                  <Label
                    htmlFor="email"
                    className="block text-sm/6 font-medium text-gray-900"
                  >
                    Email address
                  </Label>
                  <div className="mt-2">
                    <Input
                      id="email"
                      type="email"
                      placeholder="example@mail.com"
                      autoComplete="email"
                      required
                      className="block w-full rounded-md bg-white px-3 py-1.5 text-base text-gray-900 outline-1 -outline-offset-1 outline-gray-300 placeholder:text-gray-400 focus:outline-2 focus:-outline-offset-2 focus:outline-darkBlue sm:text-sm/6"
                      {...register("email")}
                      onChange={handleEmailChange}
                    />
                    {errors.email &&
                      typeof errors.email.message === "string" && (
                        <div className="text-red-500">
                          {errors.email.message}
                        </div>
                      )}
                  </div>
                </div>
                <div>
                  <div className="flex items-center justify-between">
                    <Label
                      htmlFor="password"
                      className="block text-sm/6 font-medium text-gray-900"
                    >
                      Password
                    </Label>
                    <div className="text-sm">
                      <Link
                        href="/resetPassword"
                        className="font-semibold text-darkBlue hover:text-liteBlue"
                        onClick={(e) => {
                          e.preventDefault();
                          handleResetPassword(email);
                        }}
                      >
                        Forgot password?
                      </Link>
                    </div>
                  </div>
                  <div className="mt-2 relative">
                    <Input
                      id="password"
                      type={passwordVisible ? "text" : "password"}
                      {...register("password")}
                      autoComplete="current-password"
                      placeholder="Enter your password"
                      required
                      className="block w-full rounded-md bg-white px-3 py-1.5 text-base text-gray-900 outline-1 -outline-offset-1 outline-gray-300 placeholder:text-gray-400 focus:outline-2 focus:-outline-offset-2 focus:outline-darkBlue sm:text-sm/6"
                      aria-label="Toggle password visibility"
                    />
                    {passwordVisible ? (
                      <Eye
                        className="absolute top-1/2 right-5 transform translate-x-1/2 -translate-y-1/2 w-5 cursor-pointer"
                        onClick={() => setPasswordVisible(!passwordVisible)}
                      />
                    ) : (
                      <EyeOff
                        className="absolute top-1/2 right-6 transform translate-x-1/2 -translate-y-1/2 w-5 cursor-pointer"
                        onClick={() => setPasswordVisible(!passwordVisible)}
                      />
                    )}
                  </div>
                  {errors.password &&
                    typeof errors.password.message === "string" && (
                      <div className="text-red-500">
                        {errors.password.message}
                      </div>
                    )}
                </div>

                <Button
                  type="submit"
                  className="w-full bg-darkBlue hover:bg-liteBlue text-white"
                >
                  Sign in
                </Button>

                <Button
                  type="button"
                  variant="outline"
                  className="w-full border-2 flex items-center justify-center space-x-2"
                  onClick={handleSignIn}
                >
                  <Image
                    src={google}
                    width={18}
                    height={18}
                    alt="google"
                    className="mr-2"
                  />
                  <span>Sign in with Google</span>
                </Button>
              </form>
            </CardContent>

            <CardFooter className="text-center">
              <p className="text-sm w-full">
                Don&apos;t have an account?{" "}
                <Link
                  href="/login/signup"
                  className="text-darkBlue hover:text-liteBlue"
                >
                  Sign up
                </Link>
              </p>
            </CardFooter>
          </Card>
        </div>
      </section> */}
    </>
  );
};

export default LoginForm;
