"use client";
import { useEffect, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import { usePathname } from "next/navigation";
import Link from "next/link";
import Image from "next/image";
import { motion, AnimatePresence } from "framer-motion";
import {
  LayoutDashboard,
  Users,
  Clock,
  CheckCircle,
  Building2,
  Settings,
  Power,
} from "lucide-react";
import { useScreenSizeContext } from "@/src/utils/providers/screenSizesContext";
import type { RootState } from "@/src/redux/store";
import { setSidebarOpen } from "@/src/redux/appActions";
import Overlay from "../reusables/overlay/overlay";
import { toast } from "react-toastify";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { useAppSelector } from "@/src/redux/hook";
import { logout } from "@/src/redux/authSlice";
import { PURGE } from "redux-persist";
import axiosInstance from "@/lib/axios";

const sidebarItems = [
  { icon: LayoutDashboard, label: "Dashboard", href: "/admin/dashboard" },
  { icon: Users, label: "Customers", href: "/admin/customers" },
  // {
  //   icon: Clock,
  //   label: "Pending verification",
  //   href: "/admin/pending-verification",
  // },
  // {
  //   icon: CheckCircle,
  //   label: "Verified addresses",
  //   href: "/admin/verified-addresses",
  // },
  {
    icon: Building2,
    label: "Deleted accounts",
    href: "/admin/deleted-accounts",
  },
  { icon: Settings, label: "Settings", href: "/admin/settings" },
];

export default function AdminSidebar() {
  const dispatch = useDispatch();
  const pathname = usePathname();
  const { isMobile, isTablet } = useScreenSizeContext();
  const sidebarOpen = useSelector(
    (state: RootState) => state.counter.sidebarOpen
  );
  const sidebarRef = useRef<HTMLDivElement>(null);

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

  console.log(email, "is email");

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        isMobile &&
        sidebarOpen &&
        sidebarRef.current &&
        !sidebarRef.current.contains(event.target as Node)
      ) {
        dispatch(setSidebarOpen(false));
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [isMobile, sidebarOpen, dispatch]);

  const sidebarVariants = {
    open: {
      x: 0,
      transition: { type: "spring" as const, stiffness: 300, damping: 30 },
    },
    closed: {
      x: "-100%",
      transition: { type: "spring" as const, stiffness: 300, damping: 30 },
    },
  };

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

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

      if (!adminToken) {
        return;
      }

      const response = await axiosInstance.post(`/superadmin/logout`, {
        email,
        verification_token: adminToken,
      });

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

        localStorage.clear();

        dispatch(logout());
        dispatch({ type: PURGE, key: "auth" });

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

  return (
    <>
      {/* Overlay for mobile */}
      {(isMobile || isTablet) && sidebarOpen && (
        <Overlay func={() => dispatch(setSidebarOpen(false))} />
      )}

      <AnimatePresence>
        {/* Sidebar */}
        <motion.div
          ref={sidebarRef}
          className={`fixed lg:relative z-50 h-full bg-[#16166C] text-white w-64 flex flex-col ${
            !isMobile && !isTablet ? "block" : ""
          }`}
          initial={isMobile || isTablet ? "closed" : "open"}
          animate={
            sidebarOpen ? "open" : isMobile || isTablet ? "closed" : "open"
          }
          variants={sidebarVariants}
        >
          {/* Logo */}
          <Link
            href={"/"}
            className="p-4 flex items-center gap-2 h-24 border-b border-[#16166C]"
          >
            <div className="relative w-10 h-10">
              <Image
                src="/logo.svg"
                fill
                style={{ objectFit: "contain" }}
                alt="logo"
              />
            </div>
            <span className="text-[16px] font-medium">Online Dating Site</span>
          </Link>

          {/* Navigation */}
          <div className="flex-1 overflow-y-auto py-4">
            <nav className="space-y-1 px-2">
              {sidebarItems.map((item) => {
                const isActive = pathname.includes(item.href);
                return (
                  <Link
                    key={item.href}
                    href={item.href}
                    className={`flex items-center gap-3 font-semibold text-[12px] px-4 py-3 rounded-md transition-colors md:w-[85%] mx-auto my-6 ${
                      isActive
                        ? "bg-white text-[#16166C]"
                        : "text-white hover:bg-white hover:text-[#16166C]"
                    }`}
                  >
                    <item.icon size={20} />
                    <span>{item.label}</span>
                  </Link>
                );
              })}
            </nav>
          </div>

          <div className="flex justify-start items-start w-full">
            <Button
              onClick={handleLogout}
              className={`flex items-center gap-3 font-semibold bg-transparent hover:bg-[#16166C]/85 cursor-pointer text-[12px] px-4 py-3 w-full -ml-4 rounded-md transition-colors mx-auto my-6`}
            >
              <div className="w-full flex justify-start gap-x-4 md:px-8 px-6 items-center">
                <Power size={20} />
                <span>Logout</span>
              </div>
            </Button>
          </div>
        </motion.div>
      </AnimatePresence>
    </>
  );
}
