"use client";

import React, { useMemo, useRef, useState } from "react";
import Link from "next/link";

import styles from "@/components/administrator/Sidebar/sidebar.module.css";
import { dashboardPages } from "@/config/admin";
import { usePathname } from "next/navigation";
import { AnimatePresence, motion } from "framer-motion";

import { PiUserCircleDuotone } from "react-icons/pi";
import { useOutsideClick } from "@/hooks/useOutsideClick";
import { isEmptyObject } from "@/app/library/library";
import { useRouter } from "next/navigation";
import { logout } from "@/services/auth";

/**
 *
 * @type {React.FC <{
 *    user: object;
 * }>}
 */
const Sidebar = (props) => {
  const router = useRouter();
  const userDetailRef = useRef(null);
  const pathname = usePathname();
  const [hide, setHide] = useState(true);
  const [userShow, setUserShow] = useState(false);

  const userData = useMemo(() => props.user, [props.user]);
  const pages = useMemo(() => {
    const filterRoute = (pageList, role) => {
      return pageList
        .filter((page) => page.role.includes(role) && !page.api)
        .map((page) => ({
          ...page,
          ...(page?.children?.length > 0
            ? { children: filterRoute(page.children, role) }
            : {}),
        }));
    };

    if (!userData) return dashboardPages;

    return filterRoute(dashboardPages, userData.role);
  }, [userData]);
  const currentSubSidebar = useMemo(() => {
    const thePath = Array(pathname.split("/").filter((s) => s).length)
      .fill()
      .map(
        (_, index) =>
          `/${pathname
            .split("/")
            .filter((s) => s)
            .slice(0, index + 1)
            .join("/")}`
      );
    const pathlist = [];
    const searchCurrent = (path, pages, depth) => {
      const current = pages.find((page) => {
        if (path[depth] === page.route) {
          pathlist.push(path[depth]);
          return true;
        }

        if (page.children.map((child) => child.route).includes(path[depth])) {
          pathlist.push(page.route, path[depth]);
          return true;
        }
      });

      if (!current) return searchCurrent(path, pages, depth - 1);
      return current;
    };

    const current = searchCurrent(thePath, pages, thePath.length - 1);
    return { current: pathlist, ...current };
  }, [pathname, pages]);

  useOutsideClick(userDetailRef, () => setUserShow(false));

  return (
    <AnimatePresence>
      <div className={styles.sidebar}>
        <div className={styles.main_sidebar}>
          {pages.map((page, index) => (
            <Link
              href={page.route}
              key={index}
              title={page.label}
              onMouseEnter={() => setHide(false)}
              onMouseLeave={() => setHide(true)}
              className={`${styles.menu} ${
                (pathname === page.route ||
                  currentSubSidebar.current?.[0] === page.route) &&
                styles.active
              }`}>
              <div className={styles.icon}>{page.icon}</div>
              <div className={`${styles.label} ${hide && styles.hide}`}>
                <p style={{ paddingLeft: "20px", paddingRight: "40px" }}>
                  {page.label}
                </p>
              </div>
            </Link>
          ))}
          {!isEmptyObject(userData) && (
            <div className={styles.user}>
              <AnimatePresence>
                {userShow && (
                  <motion.div
                    ref={userDetailRef}
                    initial={{ y: 10, opacity: 0 }}
                    animate={{ y: 0, opacity: 1 }}
                    exit={{ y: -10, opacity: 0 }}
                    transition={{ duration: 0.2 }}
                    className={styles.user_overlay}>
                    <div className={styles.user_image}>
                      <PiUserCircleDuotone />
                    </div>
                    <h5>{userData.name}</h5>
                    <button
                      onClick={async (e) => {
                        try {
                          e.currentTarget.disabled = true;

                          setUserShow(false);
                          logout(userData._id);
                          setTimeout(() => router.refresh());
                        } catch (error) {
                          console.log(error);
                        }
                      }}>
                      Logout
                    </button>
                  </motion.div>
                )}
              </AnimatePresence>
              <div
                className={styles.avatar}
                onClick={() => setUserShow(!userShow)}>
                <PiUserCircleDuotone />
              </div>
            </div>
          )}
        </div>
        <AnimatePresence>
          {currentSubSidebar?.children.length > 0 && (
            <motion.div
              initial={{ width: 0 }}
              animate={{ width: "240px" }}
              exit={{ width: 0 }}
              transition={{ duration: 0.6, ease: "backOut" }}
              className={styles.sub_sidebar}>
              <div className={styles.sub_sidebar_container}>
                <div className={styles.sub_sidebar_title}>
                  <h4>{currentSubSidebar.label}</h4>
                  {currentSubSidebar.description && (
                    <p>{currentSubSidebar.description}</p>
                  )}
                </div>
                <div className={styles.sub_sidebar_content}>
                  {currentSubSidebar.children.map((child, index) => (
                    <Link
                      href={child.route}
                      key={index}
                      title={child.label}
                      className={`${styles.menu} ${
                        (pathname === child.route ||
                          currentSubSidebar.current?.[1] === child.route) &&
                        styles.active
                      }`}>
                      <div className={styles.icon}>{child.icon}</div>
                      <div className={`${styles.label}`}>
                        <p style={{ marginLeft: "10px", marginRight: "10px" }}>
                          {child.label}
                        </p>
                      </div>
                    </Link>
                  ))}
                </div>
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    </AnimatePresence>
  );
};

export default Sidebar;
