"use client";
import React, { useEffect, useState } from "react";
import {
  Menu,
  Grip,
  CircleUser,
  Heart,
  ScrollText,
  HeartPulse,
  Cog,
  Power,
} from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import Overlay from "../../overlay/overlay";
import { toast } from "react-toastify";
import { useAppDispatch, useAppSelector } from "@/src/redux/hook";
import { resetProfile, setPreviewSrc, setProfilePicture } from "@/src/redux/profileSlice";
import axiosInstance from "@/lib/axios";
import { logout } from "@/src/redux/authSlice";
import { resetMatchupProfile } from "@/src/redux/matchProfileSlice";

interface MenuItem {
  id: number;
  icon: React.ReactNode;
  label: string;
  href: string;
}

const menuItems: MenuItem[] = [
  { id: 1, icon: <Grip />, label: "Dashboard", href: "/user/dashboard" },
  { id: 2, icon: <CircleUser />, label: "My Profile", href: "/user/profile" },
  { id: 3, icon: <Heart />, label: "Favourites", href: "/user/favourites" },
  { id: 4, icon: <Grip />, label: "My Mutuals", href: "/user/mutuals" },
  {
    id: 5,
    icon: <ScrollText />,
    label: "My Subscribed",
    href: "/user/subscribed",
  },
  {
    id: 6,
    icon: <HeartPulse />,
    label: "Interested in me",
    href: "/user/interested-in-me",
  },
  { id: 7, icon: <Cog />, label: "Settings", href: "/user/settings" },
  { id: 8, icon: <Power />, label: "Logout", href: "#" },
];

export default function Sidebar() {
  const [activeItem, setActiveItem] = useState<number | null>(1);
  const [isSidebarOpen, setIsSidebarOpen] = useState<boolean>(false);
  const email = useAppSelector((state) => state.auth.email);

  const router = useRouter();
  const dispatch = useAppDispatch();
  const handleClick = (id: number, href: string) => {
    setActiveItem(id);
    setIsSidebarOpen(false);
    router.push(href);
  };

  useEffect(() => {
    const handleOutsideClick = (e: MouseEvent) => {
      const sidebar = document.getElementById("sidebar");
      const hamburger = document.getElementById("menu");
      if (
        sidebar &&
        !sidebar.contains(e.target as Node) &&
        hamburger &&
        !hamburger.contains(e.target as Node)
      ) {
        setIsSidebarOpen(false);
      }
    };

    document.addEventListener("mousedown", handleOutsideClick);

    // Prevents scrolling when sidebar is open
    if (isSidebarOpen) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "auto";
    }

    return () => {
      document.removeEventListener("mousedown", handleOutsideClick);
      document.body.style.overflow = "auto"; // Reset on unmount
    };
  }, [isSidebarOpen]);

  const sidebarVariants = {
    hidden: {
      x: -300,
      opacity: 0,
    },
    visible: {
      x: 0,
      opacity: 1,
      transition: {
        type: "spring" as const,
        stiffness: 100,
        damping: 20,
        duration: 1,
      },
    },
    exit: {
      x: -300,
      opacity: 0,
      transition: {
        duration: 0.5,
        ease: "easeInOut" as const,
      },
    },
  };

  const handleLogout = async () => {
    try {
      if (typeof window === "undefined") return;

      const userToken = localStorage.getItem("userToken");

      if (!userToken) {
        return;
      }

      const response = await axiosInstance.post(
        `/logout`, // <-- Update this if `forgot-password` was a mistake
        {
          email,
          verification_token: userToken,
        }
      );

      if (response.data?.status === "success") {
        toast.success(response.data?.message || "Logged out successfully!");

        dispatch(logout());
        localStorage.removeItem("userToken");
        localStorage.clear();

        dispatch(resetMatchupProfile());
        dispatch(resetProfile());

        router.push("/");
        
      } else {
        toast.error(response.data?.message || "Logout failed.");
      }
    } catch (error: any) {
      toast.error(
        error.response?.data?.message || "An error occurred. Please try again."
      );
    }
  };

  const profilePicture = useAppSelector(
    (state) => state.profile.profilePicture
  );
  const userProfile = useAppSelector((state) => state.profile.userProfile);
  const previewSrc = useAppSelector((state) => state.profile.previewSrc);

  useEffect(() => {
    let objectUrl: string | undefined;

    if (profilePicture instanceof File) {
      objectUrl = URL.createObjectURL(profilePicture);
      dispatch(setPreviewSrc(objectUrl));
    } else if (
      typeof profilePicture === "string" &&
      profilePicture.trim() !== ""
    ) {
      dispatch(setPreviewSrc(profilePicture));
    } else if (
      typeof userProfile?.photo === "string" &&
      userProfile.photo.trim() !== ""
    ) {
      dispatch(setPreviewSrc(userProfile.photo));
    } else {
      dispatch(setPreviewSrc(undefined));
    }

    return () => {
      if (objectUrl) {
        URL.revokeObjectURL(objectUrl);
      }
    };
  }, [profilePicture, userProfile]);

  return (
    <>
      <Menu
        id="menu"
        className="sticky mt-12 ml-6 lg:top-[5%] md:top-[5%] top-[2%] left-[0%] cursor-pointer z-30"
        onClick={() => setIsSidebarOpen(!isSidebarOpen)}
      />

      <AnimatePresence>
        {isSidebarOpen && (
          <>
            <Overlay func={() => setIsSidebarOpen(false)} />

            <motion.nav
              id="sidebar"
              className="w-[300px] py-8 fixed lg:top-[15%] md:top-[22%] top-[20%] left-[3%] lg:min-h-[600px] md:min-h-[600px] bg-white shadow shadow-[#00000040] text-black rounded-md z-50 max-h-[75vh] overflow-y-auto -webkit-overflow-scrolling-touch thin-scrollbar"
              initial="hidden"
              animate="visible"
              exit="exit"
              variants={sidebarVariants}
            >
              <div className="w-full flex gap-y-4 flex-col justify-center px-4">
                <motion.div
                  className="flex flex-col gap-y-4 items-center"
                  initial={{ opacity: 0, scale: 0.9 }}
                  animate={{ opacity: 1, scale: 1 }}
                  transition={{ delay: 0.3, duration: 0.6 }}
                >
                  <div className="w-[4rem] h-[4rem] relative rounded-full flex items-center justify-center">
                    {previewSrc && (
                      <Image
                        src={previewSrc}
                        alt="profile"
                        className="rounded-full object-cover"
                        fill
                      />
                    )}
                  </div>
                  <div>
                    <span className="text-[16px] font-semibold">
                      {userProfile?.first_name}
                    </span>
                  </div>
                </motion.div>

                <div className="flex flex-col mt-2 max-w-[80%] m-auto">
                  <ul className="list-none flex flex-col gap-y-4">
                    {menuItems.map((item) => {
                      const isActive = activeItem === item.id;
                      const commonClasses = `px-6 py-3 flex gap-x-4 items-center font-semibold rounded-md cursor-pointer transition-colors duration-200 ${
                        isActive
                          ? "bg-[#EF2424] text-white"
                          : "hover:bg-gray-100"
                      }`;

                      return (
                        <li
                          key={item.id}
                          className={commonClasses}
                          onClick={() => {
                            if (item.label === "Logout") {
                              handleLogout();
                            } else {
                              handleClick(item.id, item.href);
                            }
                          }}
                        >
                          <span>{item.icon}</span>

                          {item.label === "Logout" ? (
                            <button className="text-[14px] bg-transparent border-none p-0 m-0 text-left">
                              {item.label}
                            </button>
                          ) : (
                            <Link href={item.href} className="text-[14px]">
                              {item.label}
                            </Link>
                          )}
                        </li>
                      );
                    })}
                  </ul>
                </div>
              </div>
            </motion.nav>
          </>
        )}
      </AnimatePresence>
    </>
  );
}
