"use client";
import React, { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import Link from "next/link";
import { setJoinState, setIsLogin } from "@/src/redux/appActions";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "@/src/redux/store";
import { useRouter } from "next/navigation";
import axios from "axios";
import Image from "next/image";
import LoadingSpinner from "../../reusables/ui/LoadingSpinner";
import { toast } from "react-toastify";
import { useAppDispatch, useAppSelector } from "@/src/redux/hook";
import { setEmail, setIsLoggedIn, setPassword } from "@/src/redux/authSlice";
import axiosInstance from "@/lib/axios";
import AuthGuard from "../../reusables/auth";
import { EyeOff, Eye } from "lucide-react";

export default function Login() {
  const join = useSelector((state: RootState) => state.counter.isJoining);
  const login = useSelector((state: RootState) => state.counter.login);
  const [auth2, setAuth2] = useState<boolean>(false);
  const route = useRouter();
  const dispatch = useAppDispatch();

  // auth states
  const email = useAppSelector((state) => state.auth.email);
  const password = useAppSelector((state) => state.auth.password);
  const confirmPassword = useAppSelector((state) => state.auth.confirmPassword);
  const userProfile = useAppSelector((state) => state.profile.userProfile);
  const userToken = useAppSelector((state) => state.auth.userToken);
  const token = useAppSelector((state) => state.auth.token);
  const [isLoading, setIsLoading] = useState(false);
  const [agreedToTerms, setAgreedToTerms] = useState(false);

  const [showPassword, setShowPassword] = useState<boolean>(false);

  const [errors, setErrors] = useState({
    email: "",
    password: "",
    confirmPassword: "",
    token: "",
    terms: "",
  });

  //   const handleLoginPop = () => {
  //     dispatch(setJoinState(true));
  //     dispatch(setIsLogin());
  //   };

  const handleError = (error: unknown) => {
    if (axios.isAxiosError(error)) {
      const errorData = error.response?.data;
      if (errorData?.errors) {
        const firstField: any = Object.keys(errorData.errors)[0];
        const firstMessage = errorData.errors[firstField][0];
        toast.error(firstMessage);
      } else if (errorData?.message) {
        toast.error(errorData.message);
      }
    } else {
      toast.error("Something went wrong. Please try again.");
    }
  };

  const handleLogin = async (): Promise<boolean> => {
    try {
      setIsLoading(true);
      const apiUrl = process.env["NEXT_PUBLIC_DEV_URL"];

      const response = await axios.post(`${apiUrl}/superadmin/login`, {
        email,
        password,
      });

      const token = response?.data?.payload?.token;

      if (response.data?.status === "success" && token) {
        localStorage.setItem("adminToken", token);

        toast.success(response.data?.message || "Login successful!");
        dispatch(setIsLoggedIn(true));
        return true;
      }

      return false;
    } catch (error) {
      handleError(error);
      return false;
    } finally {
      setIsLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    // Step 1: Validate input fields
    let formErrors: typeof errors = {
      email: "",
      password: "",
      confirmPassword: "",
      token: "",
      terms: "",
    };

    if (!email) formErrors.email = "Email is required";
    if (!password) formErrors.password = "Password is required";

    setErrors(formErrors);
    const hasErrors = Object.values(formErrors).some((err) => err);
    if (hasErrors) return;

    // Step 3: Proceed with the correct flow
    // if (login) {
    const loggedIn = await handleLogin();
    if (loggedIn) {
      route.push("/admin/dashboard");
    }
    // }
  };

  return (
    <AuthGuard>
      <header className="w-full header-admin flex flex-col gap-y-6 text-white font-inter relative z-[10]">
        <div className="absolute inset-0 bg-black/30 z-0 pointer-events-none" />

        <div className="h-32 flex items-center z-10">
          <section className="w-full py-8 h-full px-12 flex items-center">
            <div className="w-40 h-full flex items-center gap-2">
              <div className="relative aspect-square h-3/4">
                <Image
                  src="/images/logo.svg"
                  style={{ objectFit: "contain" }}
                  alt="logo"
                  width={50}
                  height={50}
                />
              </div>
              <Link
                href={"/"}
                className="text-[20px] whitespace-nowrap font-jaini"
              >
                Happy Homes
              </Link>
            </div>
          </section>
        </div>

        <div
          className="flex lg:flex-row flex-col lg:gap-x-5 lg:gap-y-0 gap-y-12 items-center my-8 z-[10] px-12"
          id="join_now"
        >
          <section className="lg:w-[50%] w-full flex flex-col justify-start items-start">
            <div className="w-full lg:max-w-[80%] max-w-[100%]  text-left flex flex-col gap-y-6">
              <div className="md:w-[400px] md:h-[201px] flex flex-col gap-[20px]">
                <h1 className="text-4xl font-semibold font-inter text-[48px]">
                  Discover Your Perfect Partner
                </h1>
                <p className="text-2xl font-inter text-[20px]">
                  Explore our site and see why it&apos;s one of the fastest
                  growing companion sites. we are empowering the world to find
                  love, friendship and users to find their perfect partners
                </p>

                {/* {!join && (
                <div className="mt-6">
                  <Button
                    className="bg-[#16166C] hover:bg-[#16166C]/85 p-[10px] cursor-pointer"
                    onClick={handleLoginPop}
                  >
                    Login Now
                  </Button>
                </div>
              )} */}
              </div>
            </div>
          </section>
          (
          <section className="lg:w-[40%] w-full flex flex-col lg:items-center md:items-start justify-center items-center">
            <form
              onSubmit={handleSubmit}
              action=""
              className="flex flex-col gap-y-4 bg-white lg:min-h-[500px] md:min-h-[400px] min-h-[350px] text-black rounded-md shadow w-[95%] shadow-[#000000] md:px-16 px-8 py-12 md:w-3/4"
            >
              <div className="flex flex-col gap-y-3 w-full">
                <h1 className="text-2xl text-[24px] font-[600]">
                  {login ? "Login" : "Sign up"}
                </h1>
                <p className="font-[600] !text-[16px]">
                  Login as administrator
                </p>
              </div>

              <div className="w-full flex flex-col gap-y-4">
                {/* Login */}
                {/* {login && !auth2 && (
                <> */}
                {/* Email */}
                <div className="my-1 flex flex-col gap-y-1">
                  <Input
                    type="text"
                    id="email"
                    className={`border p-2 md:!text-[12px] !text-[14px] font-[600] ${
                      errors.email ? "border-red-500" : "border-[#D9D9D9]"
                    }`}
                    placeholder="email"
                    value={email}
                    onChange={(e) => {
                      dispatch(setEmail(e.target.value));
                      setErrors({ ...errors, email: "" });
                    }}
                  />
                  {errors.email && (
                    <p className="text-red-500 text-xs mt-1">{errors.email}</p>
                  )}
                </div>

                {/* Password */}
                <div className="my-1 flex flex-col gap-y-1">
                  <div className="relative">
                    <Input
                      type={showPassword ? "text" : "password"}
                      id="password"
                      className={`border p-2 md:!text-[12px] !text-[14px] font-[600] ${
                        errors.password ? "border-red-500" : "border-[#D9D9D9]"
                      }`}
                      placeholder="password"
                      value={password}
                      onChange={(e) => {
                        dispatch(setPassword(e.target.value));
                        setErrors({ ...errors, password: "" });
                      }}
                    />
                    <button
                      type="button"
                      className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500 hover:text-gray-700 focus:outline-none cursor-pointer"
                      onClick={() => setShowPassword(!showPassword)}
                    >
                      {showPassword ? <EyeOff size={16} /> : <Eye size={16} />}
                    </button>
                  </div>
                  {errors.password && (
                    <p className="text-red-500 text-xs mt-1">
                      {errors.password}
                    </p>
                  )}
                </div>
                {/* </>
              )} */}
              </div>

              {/* Submit Button */}
              <Button
                type="submit"
                disabled={isLoading}
                className="bg-[#16166C] hover:bg-[#16166C]/85 p-[10px] cursor-pointer"
              >
                {isLoading ? (
                  <div className="flex items-center gap-2">
                    <LoadingSpinner />
                  </div>
                ) : (
                  "Login"
                )}
              </Button>

              {/* Switch Auth Mode */}
              {!auth2 && (
                <div className="flex items-center justify-between">
                  <span className="text-[12px] inline-flex items-center">
                    Forgot password?
                    <Button
                      type="button"
                      className="text-[#192CCF] text-[12px] cursor-pointer bg-transparent shadow-none hover:bg-transparent px-1 py-0"
                      onClick={() => dispatch(setIsLogin())}
                    ></Button>
                  </span>
                  {/* 
                {login && ( */}
                  <Link href="/admin/forgot-password">
                    <Button
                      type="button"
                      className="text-[#192CCF] text-[12px] cursor-pointer bg-transparent shadow-none hover:bg-transparent px-1 py-0"
                    >
                      Reset Password
                    </Button>
                  </Link>
                  {/* )} */}
                </div>
              )}
            </form>
          </section>
        </div>
      </header>
    </AuthGuard>
  );
}
