"use client";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import LoadingSpinner from "@/src/components/reusables/ui/LoadingSpinner";
import {
  setConfirmPassword,
  setEmail,
  setPassword,
} from "@/src/redux/authSlice";
import { useAppDispatch, useAppSelector } from "@/src/redux/hook";
import axios from "axios";

import { toast } from "react-toastify";
import Image from "next/image";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import React, { useEffect, useState } from "react";
import { setJoinState } from "@/src/redux/appActions";
import { EyeOff, Eye } from "lucide-react";
import { FiMenu, FiX } from "react-icons/fi";

const ResetPassword = () => {
  const [isLoading, setIsLoading] = useState(false);

  const email = useAppSelector((state) => state.auth.email);
  const password = useAppSelector((state) => state.auth.password);
  const confirmPassword = useAppSelector((state) => state.auth.confirmPassword);

  const [isOpen, setIsOpen] = useState(false);

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

  const router = useRouter();
  const dispatch = useAppDispatch();
  const searchParams = useSearchParams();

  const token = searchParams.get("token");
  const emailFromUrl = searchParams.get("email");

  useEffect(() => {
    if (emailFromUrl) {
      dispatch(setEmail(emailFromUrl));
    }
  }, [emailFromUrl, dispatch]);

  const handlePasswordReset = async (e: any) => {
    e.preventDefault();

    try {
      setIsLoading(true);
      const apiUrl = process.env["NEXT_PUBLIC_DEV_URL"];

      const response: any = await axios.post(`${apiUrl}/reset-password`, {
        reset_token: token,
        email: emailFromUrl,
        password: password,
        password_confirmation: confirmPassword,
      });

      if (response.data?.status === "success") {
        toast.success(response.data?.message || "Password reset successfully!");
        router.push("/");
        dispatch(setJoinState(true));
      } else {
        toast.error(
          response.data?.errors?.password?.[0] ||
            response.data?.message ||
            "Failed to reset password."
        );
      }
    } catch (error: any) {
      console.error("Reset password error:", error);
      toast.error(
        error.response?.data?.message ||
          "An error occurred while resetting your password. Please try again."
      );
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <header className="w-full header 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 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>

      <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-[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>
          </div>
        </section>

        <section className="lg:w-[40%] w-full flex flex-col lg:items-center md:items-start justify-center items-center">
          <form
            onSubmit={handlePasswordReset}
            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-lg mb-3 font-[600]">Reset Your Password</h1>
            </div>

            <div className="w-full flex flex-col gap-y-4">
              <>
                {/* Email */}
                <div className="my-1 flex flex-col gap-y-1">
                  <Input
                    id="mail"
                    className={`border p-2 md:!text-[12px] !text-[14px] font-[600] ${"border-[#D9D9D9]"}`}
                    type="email"
                    value={email}
                    readOnly
                  />
                </div>

                <div className="my-1 flex flex-col gap-y-1">
                  <div className="relative">
                    <Input
                      id="password"
                      type={showPassword.password ? "text" : "password"}
                      placeholder="Enter Password"
                      className={`border p-2 md:!text-[12px] !text-[14px] font-[600] ${"border-[#D9D9D9]"}`}
                      value={password}
                      onChange={(e) => dispatch(setPassword(e.target.value))}
                    />
                    <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>
                </div>

                <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] ${"border-[#D9D9D9]"}`}
                      placeholder="Confirm password"
                      id="confirm_password"
                      value={confirmPassword}
                      onChange={(e) =>
                        dispatch(setConfirmPassword(e.target.value))
                      }
                    />
                    <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>
                </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>
              ) : (
                "Submit"
              )}
            </Button>
          </form>
        </section>
      </div>
    </header>
  );
};

export default ResetPassword;
