"use client";

import type React from "react";
import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/checkbox";
import Link from "next/link";
import { setJoinState, setIsLogin } from "@/src/redux/appActions";
import { useSelector } from "react-redux";
import type { 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 { FiMenu, FiX } from "react-icons/fi";
import {
  setAvaliableTry,
  setConfirmPassword,
  setEmail,
  setIsBiodataSetup,
  setIsContactSetup,
  setIsHobbiesSetup,
  setIsLoggedIn,
  setIsPersonalSetup,
  setPassword,
  setToken,
  setUserToken,
} from "@/src/redux/authSlice";
import { EyeOff, Eye } from "lucide-react";
import { setUserProfile } from "@/src/redux/profileSlice";
import { motion, AnimatePresence } from "framer-motion";

// Sample images for the slider
const sliderImages = [
  "/images/slider-1.svg",
  "/images/slider-2.svg",
  "/images/slider-3.svg",
];

export default function Header() {
  const join = useSelector((state: RootState) => state.counter.isJoining);
  const login = useSelector((state: RootState) => state.counter.login);
  const isLoggedIn = useAppSelector(
    (state: RootState) => state.auth.isLoggedIn
  );
  const [auth2, setAuth2] = useState<boolean>(false);

  // Slider state
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isTransitioning, setIsTransitioning] = useState(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 isBiodataSetup = useAppSelector((state) => state.auth.isBioDataSetup);
  const isPersonalSetup = useAppSelector((state) => state.auth.isPersonalSetup);
  const isContactSetup = useAppSelector((state) => state.auth.isContactSetup);
  const isHobbiesSetup = useAppSelector((state) => state.auth.isHobbiesSetup);

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

  const [showPassword, setShowPassword] = useState<{
    password: boolean;
    confirmPassword: boolean;
  }>({ password: false, confirmPassword: false });

  const [showLoginPassword, setShowLoginPassword] = useState<boolean>(false);
  const [isOpen, setIsOpen] = useState(false);

  // Slider auto-advance effect
  useEffect(() => {
    if (!join) {
      const interval = setInterval(() => {
        setIsTransitioning(true);
        setTimeout(() => {
          setCurrentIndex((prevIndex) =>
            prevIndex >= sliderImages.length - 1 ? 0 : prevIndex + 1
          );
          setIsTransitioning(false);
        }, 500); // Half of transition duration
      }, 4000);

      return () => clearInterval(interval);
    }
    return;
  }, [join]);

  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 handleRegister = async (): Promise<boolean> => {
    try {
      setIsLoading(true);
      const apiUrl = process.env["NEXT_PUBLIC_DEV_URL"];

      const response = await axios.post(`${apiUrl}/register`, {
        email,
        password,
        password_confirmation: confirmPassword,
        accept_terms: agreedToTerms,
      });

      if (response.data?.status === "success") {
        toast.success(response.data?.message || "Registration successful!");
        return true;
      }

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

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

      const response = await axios.post(`${apiUrl}/verify`, {
        email,
        verification_token: token,
      });

      const userToken = response?.data?.payload?.token;
      const userId = response?.data?.payload?.profile.user_id;

      if (response.data?.status === "success") {
        toast.success(response.data?.message || "Token verified successfully!");
        localStorage.setItem("userToken", userToken);
        localStorage.setItem("userId", userId);

        dispatch(setUserProfile(response?.data?.payload?.profile));
        dispatch(setIsLoggedIn(true));
        return true;
      }

      dispatch(setUserToken(response.data.payload.token));
      dispatch(setIsBiodataSetup(response.data.payload.biodata_setup));
      dispatch(setIsHobbiesSetup(response.data.payload.hobbies_interest_setup));
      dispatch(setIsContactSetup(response.data.payload.contact_setup));
      dispatch(setIsPersonalSetup(response.data.payload.personal_setup));

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

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

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

      const token = response?.data?.payload?.token;
      const userId = response?.data?.payload?.profile.user_id;

      if (response.data?.status === "success" && token) {
        // Save token and user info to localStorage
        localStorage.setItem("userToken", token);
        localStorage.setItem("userId", userId);

        // Optionally update Redux or context state
        dispatch(setUserProfile(response?.data?.payload?.profile));
        dispatch(
          setIsBiodataSetup(response?.data?.payload?.profile?.biodata_setup)
        );
        dispatch(
          setIsHobbiesSetup(
            response?.data?.payload?.profile?.hobbies_interest_setup
          )
        );
        dispatch(
          setIsContactSetup(response?.data?.payload?.profile?.contact_setup)
        );
        dispatch(
          setIsPersonalSetup(response?.data?.payload?.profile?.personal_setup)
        );

        toast.success(response.data?.message || "Login successful!");

        dispatch(setIsLoggedIn(true));
        dispatch(setAvaliableTry(true));

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

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

    const formErrors: typeof errors = {
      email: "",
      password: "",
      confirmPassword: "",
      token: "",
      terms: "",
    };

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

    if (!login && !auth2 && !agreedToTerms) {
      formErrors.terms = "You must agree to the terms and conditions.";
    }

    if (!login && !auth2) {
      if (!confirmPassword) {
        formErrors.confirmPassword = "Please confirm your password";
      } else if (password !== confirmPassword) {
        formErrors.confirmPassword = "Passwords do not match";
      }
    }

    if (!login && auth2 && !token) {
      formErrors.token = "Token is required";
    }

    // Step 2: Update error state and stop submission if any errors exist
    setErrors(formErrors);
    const hasErrors = Object.values(formErrors).some((err) => err);
    if (hasErrors) return;

    // Step 3: Proceed with the correct flow
    if (!login && !auth2) {
      const success = await handleRegister();
      if (success) {
        setAuth2(true);
      }
    } else if (!login && auth2) {
      const verified = await handleTokenVerification();

      if (verified) {
        route.push("/user/profile-setup");
      }
    } else if (login) {
      const loggedIn = await handleLogin();
      if (loggedIn) {
        if (
          !isBiodataSetup ||
          !isPersonalSetup ||
          !isContactSetup ||
          !isHobbiesSetup
        ) {
          route.push("/user/profile-setup");
        } else {
          route.push("/user/dashboard");
        }
      }
    }
  };

  useEffect(() => {
    console.log(login, "is login");
  }, [login]);

  // Animation variants for the slider
  const slideVariants = {
    entering: {
      x: "100%",
      scale: 0.75,
      opacity: 0.8,
      zIndex: 5,
      transition: {
        duration: 1,
        ease: "easeInOut" as const,
      },
    },
    active: {
      x: "0%",
      scale: 1,
      opacity: 1,
      zIndex: 20,
      transition: {
        duration: 1.5,
        ease: "easeInOut" as const,
        delay: 0.5,
      },
    },
    exiting: {
      x: "-50%",
      scale: 0.5,
      opacity: 0.6,
      zIndex: 5,
      transition: {
        duration: 0.8,
        ease: "easeInOut" as const,
      },
    },
  };

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

      <div className="h-32 flex items-center justify-between px-6 md:px-12 z-20 relative">
        <section className="w-full h-full flex items-center justify-between">
          {/* Logo */}
          <div className="flex items-center gap-2" onClick={() => dispatch(setJoinState(false))}>
            <div className="relative aspect-square h-12 w-12 md:h-16 md:w-16">
              <Image
                src="/images/logo.svg"
                fill
                style={{ objectFit: "contain" }}
                alt="logo"
              />
            </div>
            <Link href="/">
              <div className="text-xl md:text-2xl whitespace-nowrap font-jaini">
                Happy Homes Creators
              </div>
            </Link>
          </div>

          {/* Desktop Navigation */}
          <nav className="hidden md:flex gap-x-8 items-center">
            <Link href="#about">About Us</Link>
            <Link href="/user/contact">Contact Us</Link>
          </nav>

          {/* Hamburger Menu */}
          <button
            className="md:hidden text-3xl"
            onClick={() => setIsOpen(!isOpen)}
            aria-label="Toggle Menu"
          >
            {isOpen ? <FiX className="text-black" /> : <FiMenu />}
          </button>
        </section>
      </div>

      {/* Mobile Sidebar */}
      <div
        className={`fixed top-0 right-0 h-full w-3/4 bg-white text-black shadow-md transform transition-transform duration-300 z-50 ${
          isOpen ? "translate-x-0" : "translate-x-full"
        }`}
      >
        <button
          className="absolute right-6 top-6"
          onClick={() => setIsOpen(false)}
        >
          <FiX className="text-black" size={20} />
        </button>

        <div className="flex flex-col gap-6 p-6 pt-20 text-sm">
          <Link
            href="#about"
            onClick={() => setIsOpen(false)}
            className="hover:text-red-400  ease-in-out"
          >
            About Us
          </Link>
          <Link
            href="/user/contact"
            onClick={() => setIsOpen(false)}
            className="hover:text-red-400  ease-in-out"
          >
            Contact Us
          </Link>
        </div>
      </div>

      {/* Backdrop when sidebar is open */}
      {isOpen && (
        <div
          className="fixed inset-0 bg-black/30 z-40"
          onClick={() => setIsOpen(false)}
        />
      )}

      <div
        className="flex lg:flex-row relative flex-col lg:gap-x-5 lg:gap-y-0 gap-y-12 items-center my-8 z-[10] md:px-12 px-5"
        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-[550px] lg:min-h-[410px] md:h-[201px] flex flex-col gap-[20px]">
              <h1 className="font-semibold font-inter md:text-[42px] text-[40px] leading-[55px]">
                Discover Your Perfect Partner
              </h1>
              <h1 className="font-semibold font-inter sm:text-[24px] text-[18px]">
                Uncover the Love Story You Deserve
              </h1>
              <p className="font-inter text-base leading-7">
              Welcome to Happy Home Creators! We're not just another dating site; we're a community built on shared values and genuine intentions. Our advanced matchmaking algorithm and personalized approach help you discover compatible partners, not just profiles.
              </p>

              <div className="flex gap-x-[32px]">
                {!join && (
                  <div className="mt-6">
                    <Button
                      className="bg-[#EF2424] hover:bg-[#EF2424]/85 p-[10px] cursor-pointer rounded-[5px] text-[18px] py-6 px-4"
                      onClick={() => {
                        if (isLoggedIn) {
                          route.replace("/user/dashboard");
                          return;
                        }
                        if (login) {
                          dispatch(setIsLogin());
                        }
                        dispatch(setJoinState(true));
                      }}
                    >
                      Create your profile
                    </Button>
                  </div>
                )}

                {!join && (
                  <div className="mt-6">
                    <Button
                      className="bg-[#EF2424] hover:bg-[#EF2424]/85 p-[10px] cursor-pointer rounded-[5px] text-[18px] py-6 px-4"
                      onClick={() => {
                        if (isLoggedIn) {
                          route.replace("/user/dashboard");
                          return;
                        }
                        dispatch(setJoinState(true));
                        dispatch(setIsLogin());
                      }}
                    >
                      Login
                    </Button>
                  </div>
                )}
              </div>
            </div>
          </div>
        </section>

        {/* Login/Register Form */}
        {join && (
          <section className="lg:w-[40%] w-full flex flex-col lg:items-center md:items-start justify-center items-center lg:mt-0 md:mt-8 mt-0">
            <form
              onSubmit={handleSubmit}
              action=""
              className="flex flex-col gap-y-4 bg-white lg:min-h-[500px] md:min-h-[400px] min-h-[350px] w-[95%] text-black rounded-md shadow 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 ? "Login to your account" : "Create New Account"}
                </p>
              </div>

              <div className="w-full flex flex-col gap-y-4">
                {/* Sign Up Step 1 */}
                {!auth2 && !login && (
                  <>
                    {/* Email */}
                    <div className="my-1 flex flex-col gap-y-1">
                      <Input
                        id="mail"
                        type="email"
                        className={`border p-2 md:!text-[12px] !text-[14px] font-[600] ${
                          errors.email ? "border-red-500" : "border-[#D9D9D9]"
                        }`}
                        placeholder="Enter your 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
                          name="password"
                          type={showPassword.password ? "text" : "password"}
                          className={`border p-2 pr-10 !text-[12px] font-[600] ${
                            errors.password
                              ? "border-red-500"
                              : "border-[#D9D9D9]"
                          }`}
                          placeholder="Create a password"
                          id="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,
                              password: !showPassword.password,
                            })
                          }
                        >
                          {showPassword.password ? (
                            <EyeOff size={16} />
                          ) : (
                            <Eye size={16} />
                          )}
                        </button>
                      </div>
                      {errors.password && (
                        <p className="text-red-500 text-xs mt-1">
                          {errors.password}
                        </p>
                      )}
                    </div>
                    {/* Confirm Password */}
                    <div className="my-1 flex flex-col gap-y-1">
                      <div className="relative">
                        <Input
                          type={
                            showPassword.confirmPassword ? "text" : "password"
                          }
                          className={`border p-2 md:!text-[12px] !text-[14px] font-[600] ${
                            errors.confirmPassword
                              ? "border-red-500"
                              : "border-[#D9D9D9]"
                          }`}
                          placeholder="Confirm password"
                          id="confirm_password"
                          value={confirmPassword}
                          onChange={(e) => {
                            dispatch(setConfirmPassword(e.target.value));
                            setErrors({ ...errors, confirmPassword: "" });
                          }}
                        />
                        <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,
                              confirmPassword: !showPassword.confirmPassword,
                            })
                          }
                        >
                          {showPassword.confirmPassword ? (
                            <EyeOff size={16} />
                          ) : (
                            <Eye size={16} />
                          )}
                        </button>
                      </div>
                      {errors.confirmPassword && (
                        <p className="text-red-500 text-xs mt-1">
                          {errors.confirmPassword}
                        </p>
                      )}
                    </div>
                    {/* Agreement Checkbox */}
                    <div className="my-1 flex flex-col gap-y-1">
                      <div className="flex gap-x-2 items-start">
                        <Checkbox
                          id="agree"
                          checked={agreedToTerms}
                          onCheckedChange={(checked) => {
                            setAgreedToTerms(checked as boolean);
                            setErrors({ ...errors, terms: "" });
                          }}
                        />
                        <label
                          htmlFor="agree"
                          className="text-[10px] leading-tight cursor-pointer"
                        >
                          Tick to acknowledge that you&apos;ve read and agreed
                          to our{" "}
                          <Link
                            href="/user/terms-and-conditions"
                            className="text-[#192CCF] hover:underline"
                          >
                            terms and conditions
                          </Link>{" "}
                          .
                        </label>
                      </div>
                      {errors.terms && (
                        <p className="text-red-500 text-xs mt-1">
                          {errors.terms}
                        </p>
                      )}
                    </div>
                  </>
                )}

                {/* Token Step */}
                {auth2 && !login && (
                  <div className="my-1 flex flex-col gap-y-1">
                    <Input
                      type="number"
                      className={`border p-2 ${errors.token ? "border-red-500" : "border-[#D9D9D9]"}`}
                      placeholder="Enter Your Token"
                      id="given_token"
                      value={token}
                      onChange={(e) => {
                        dispatch(setToken(e.target.value));
                        setErrors({ ...errors, token: "" });
                      }}
                    />
                    {errors.token && (
                      <p className="text-red-500 text-xs mt-1">
                        {errors.token}
                      </p>
                    )}
                  </div>
                )}

                {/* Login */}
                {login && !auth2 && (
                  <>
                    {/* Email */}
                    <div className="my-1 flex flex-col gap-y-1">
                      <Input
                        type="email"
                        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={showLoginPassword ? "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={() =>
                            setShowLoginPassword(!showLoginPassword)
                          }
                        >
                          {showLoginPassword ? (
                            <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-[#EF2424] hover:bg-[#EF2424]/85 p-[10px] cursor-pointer"
              >
                {isLoading ? (
                  <div className="flex items-center gap-2">
                    <LoadingSpinner />
                  </div>
                ) : login ? (
                  "Login"
                ) : auth2 ? (
                  "Proceed"
                ) : (
                  "Sign up"
                )}
              </Button>

              {/* Switch Auth Mode */}
              {!auth2 && (
                <div className="flex md:flex-row flex-col md:items-center justify-between">
                  <span className="text-[12px]">
                    {login
                      ? "Don't have an account?"
                      : "Already have an account?"}{" "}
                    <Button
                      type="button"
                      className="text-[#192CCF] text-[12px] cursor-pointer bg-transparent shadow-none hover:bg-transparent px-1 py-0"
                      onClick={() => dispatch(setIsLogin())}
                    >
                      {login ? "Sign up" : "Login"}
                    </Button>
                  </span>

                  {login && (
                    <Link href="/user/forgot-password">
                      <Button
                        type="button"
                        className="text-[#192CCF] text-[12px] cursor-pointer bg-transparent shadow-none hover:bg-transparent px-1 py-0"
                      >
                        Forgot Password
                      </Button>
                    </Link>
                  )}
                </div>
              )}
            </form>
          </section>
        )}
      </div>

      {/* Image Slider */}
      {!join && (
        <section className="lg:max-w-[960px] w-full absolute bottom-c right-0 md:flex hidden justify-center items-center lg:mt-0 md:mt-8 mt-0">
          <div className="relative w-full h-[420px] overflow-hidden rounded-lg">
            <div className="relative w-full h-full flex items-end justify-center">
              {sliderImages.map((image, index) => {
                const isActive = index === currentIndex;
                const isNext =
                  index === (currentIndex + 1) % sliderImages.length;
                const isPrevious =
                  index ===
                  (currentIndex - 1 + sliderImages.length) %
                    sliderImages.length;

                if (!isActive && !isNext && !isPrevious) return null;

                let animationState = "entering";
                let shouldShow = true;

                // animation flow condition
                if (isActive && !isTransitioning) {
                  animationState = "active";
                } else if (isActive && isTransitioning) {
                  animationState = "exiting";
                } else if (isPrevious && isTransitioning) {
                  animationState = "exiting";
                } else if (isNext && !isTransitioning) {
                  animationState = "entering";
                } else if (isNext && isTransitioning) {
                  animationState = "active";
                } else {
                  shouldShow = false;
                }

                if (!shouldShow) return null;

                return (
                  <motion.div
                    key={`${index}`}
                    className="absolute"
                    variants={slideVariants}
                    animate={animationState}
                    exit="exiting"
                    style={{
                      right:
                        isActive || (isNext && isTransitioning) ? "25%" : "25%",
                      width: "320px",
                      height: isActive ? "420px" : "320px",
                    }}
                  >
                    <div className="relative w-full h-full rounded-2xl overflow-hidden shadow-2xl border-4 border-white">
                      <Image
                        src={image || "/placeholder.svg"}
                        alt={`Slider image ${index + 1}`}
                        fill
                        style={{ objectFit: "cover" }}
                        className="transition-transform duration-1000"
                      />
                    </div>
                  </motion.div>
                );
              })}
            </div>
          </div>
        </section>
      )}
    </header>
  );
}
