import React, { useEffect, useState } from "react";
import { Link, useLocation, useNavigate, useParams } from "react-router-dom";
import DashboardIcon from "../assets/icons/dashboardIcon";
import UsersIcon from "../assets/icons/UsersIcon";
import PostsIcon from "../assets/icons/PostsIcon";
import ProjectsIcon from "../assets/icons/ProjectsIcon";
import SupportIcon from "../assets/icons/SupportIcon";
import FinancialsIcon from "../assets/icons/FinancialsIcon";
import CommentsIcon from "../assets/icons/CommentsIcon";
import AdvertisingIcon from "../assets/icons/AdvertisingIcon";
import ShopIcon from "../assets/icons/ShopIcon";
import { GrLicense } from "react-icons/gr";

function Tooltip({ svgIcon, title }) {
  const [showTooltip, setShowTooltip] = useState(false);

  return (
    <div className="relative flex items-center justify-center">
      <span
        className="z-50 pl-2 cursor-pointer"
        onMouseEnter={() => setShowTooltip(true)}
        onMouseLeave={() => setShowTooltip(false)}
      >
        {svgIcon}
      </span>
      <div
        className={`absolute left-12 top-1/2 transform -translate-y-1/2 transition-all duration-300 ease-in-out ${
          showTooltip ? "opacity-100 translate-x-2" : "opacity-0 translate-x-0"
        }`}
      >
        <div className="relative">
          <div className="font-sans text-xs font-medium text-white bg-gray-900/80 backdrop-blur-md rounded-md px-3 py-1.5 shadow-xl">
            {title}
          </div>
          <svg
            className="absolute z-10 w-3 h-3 text-gray-900/80 transform -translate-x-2 translate-y-1 fill-current"
            width="8"
            height="8"
          >
            <rect x="0" y="2" width="8" height="8" transform="rotate(45)" />
          </svg>
        </div>
      </div>
    </div>
  );
}

const Sidebar = () => {
  const { pathname } = useLocation();
  const navigate = useNavigate();
  const param = useParams();
  const [items, setItems] = useState([]);
  const [isCollapsed, setIsCollapsed] = useState(false);

  useEffect(() => {
    setItems([
      {
        menu: "داشبورد",
        subshow: false,
        link: "/",
        submenu: [],
        icon(pathnamin) {
          return (
            <Tooltip
              svgIcon={
                <DashboardIcon
                  className={`w-6 h-6 transition-colors duration-300 ${
                    this.subshow || pathnamin === this.link
                      ? "fill-neutral-100"
                      : "fill-gray-300 group-hover:fill-neutral-100"
                  }`}
                />
              }
              title="داشبورد"
            />
          );
        },
      },
      {
        menu: "کاربران",
        link: "/users",
        subshow: false,
        submenu: [],
        icon(pathnamin) {
          return (
            <Tooltip
              svgIcon={
                <UsersIcon
                  className={`w-6 h-6 transition-colors duration-300 ${
                    this.subshow || pathnamin === this.link
                      ? "fill-neutral-100"
                      : "fill-gray-300 group-hover:fill-neutral-100"
                  }`}
                />
              }
              title="کاربران"
            />
          );
        },
      },
      {
        menu: "پست ها",
        link: "/posts",
        subshow: false,
        submenu: [],
        icon(pathnamin) {
          return (
            <Tooltip
              svgIcon={
                <PostsIcon
                  className={`w-6 h-6 transition-colors duration-300 ${
                    this.subshow || pathnamin === this.link
                      ? "fill-neutral-100"
                      : "fill-gray-300 group-hover:fill-neutral-100"
                  }`}
                />
              }
              title="پست ها"
            />
          );
        },
      },
      {
        menu: "پروژه ها",
        link: "/projects",
        subshow: false,
        submenu: [],
        icon(pathnamin) {
          return (
            <Tooltip
              svgIcon={
                <ProjectsIcon
                  className={`w-6 h-6 transition-colors duration-300 ${
                    this.subshow || pathnamin === this.link
                      ? "fill-neutral-100"
                      : "fill-gray-300 group-hover:fill-neutral-100"
                  }`}
                />
              }
              title="پروژه ها"
            />
          );
        },
      },
      {
        menu: "تیکت ها",
        link: "/tickets",
        subshow: false,
        submenu: [],
        icon(pathnamin) {
          return (
            <Tooltip
              svgIcon={
                <SupportIcon
                  className={`w-6 h-6 transition-colors duration-300 ${
                    this.subshow || pathnamin === this.link
                      ? "fill-neutral-100"
                      : "fill-gray-300 group-hover:fill-neutral-100"
                  }`}
                />
              }
              title="تیکت ها"
            />
          );
        },
      },
      {
        menu: "مالی",
        link: "/financials",
        subshow: false,
        submenu: [],
        icon(pathnamin) {
          return (
            <Tooltip
              svgIcon={
                <FinancialsIcon
                  className={`w-6 h-6 transition-colors duration-300 ${
                    this.subshow || pathnamin === this.link
                      ? "fill-neutral-100"
                      : "fill-gray-300 group-hover:fill-neutral-100"
                  }`}
                />
              }
              title="مالی"
            />
          );
        },
      },
      {
        menu: "نظرات",
        link: "/comments",
        subshow: false,
        submenu: [],
        icon(pathnamin) {
          return (
            <Tooltip
              svgIcon={
                <CommentsIcon
                  className={`w-6 h-6 transition-colors duration-300 ${
                    this.subshow || pathnamin === this.link
                      ? "fill-neutral-100"
                      : "fill-gray-300 group-hover:fill-neutral-100"
                  }`}
                />
              }
              title="نظرات"
            />
          );
        },
      },
      {
        menu: "ویترین",
        link: "/vitrine",
        subshow: false,
        submenu: [],
        icon(pathnamin) {
          return (
            <Tooltip
              svgIcon={
                <AdvertisingIcon
                  className={`w-6 h-6 transition-colors duration-300 ${
                    this.subshow || pathnamin === this.link
                      ? "fill-neutral-100"
                      : "fill-gray-300 group-hover:neutral-100"
                  }`}
                />
              }
              title="ویترین"
            />
          );
        },
      },
      {
        menu: "نظرات ویترین",
        link: "/vitrine-comments",
        subshow: false,
        submenu: [],
        icon(pathnamin) {
          return (
            <Tooltip
              svgIcon={
                <ShopIcon
                  className={`w-6 h-6 transition-colors duration-300 ${
                    this.subshow || pathnamin === this.link
                      ? "fill-gray-500"
                      : "fill-gray-300 group-hover:fill-neutral-100"
                  }`}
                />
              }
              title="نظرات ویترین"
            />
          );
        },
      },
      {
        menu: "فروشگاه",
        link: "/shops",
        subshow: false,
        submenu: [],
        icon(pathnamin) {
          return (
            <Tooltip
              svgIcon={
                <ShopIcon
                  className={`w-6 h-6 transition-colors duration-300 ${
                    this.subshow || pathnamin === this.link
                      ? "fill-neutral-100"
                      : "fill-gray-300 group-hover:fill-neutral-100"
                  }`}
                />
              }
              title="فروشگاه"
            />
          );
        },
      },
      {
        menu: "اموزشگاه",
        link: "/academy",
        subshow: false,
        submenu: [],
        icon(pathnamin) {
          return (
            <Tooltip
              svgIcon={
                <ShopIcon
                  className={`w-6 h-6 transition-colors duration-300 ${
                    this.subshow || pathnamin === this.link
                      ? "fill-neutral-100"
                      : "fill-gray-300 group-hover:fill-neutral-100"
                  }`}
                />
              }
              title="اموزشگاه"
            />
          );
        },
      },
      {
        menu: "مجوز",
        link: "/license",
        subshow: false,
        submenu: [],
        icon(pathnamin) {
          return (
            <Tooltip
              svgIcon={
                <GrLicense
                  className={`w-6 h-6 transition-colors duration-300 ${
                    this.subshow || pathnamin === this.link
                      ? "fill-neutral-100"
                      : "fill-gray-300 group-hover:fill-neutral-100"
                  }`}
                />
              }
              title="مجوز"
            />
          );
        },
      },
      {
        menu: "ورژن برنامه",
        link: "/version",
        subshow: false,
        submenu: [],
        icon(pathnamin) {
          return (
            <Tooltip
              svgIcon={
                <svg
                  className={`w-6 h-6 transition-colors duration-300 ${
                    this.subshow || pathnamin === this.link
                      ? "fill-neutral-100"
                      : "fill-gray-300 group-hover:fill-neutral-100"
                  }`}
                  xmlns="http://www.w3.org/2000/svg"
                  viewBox="0 0 24 24"
                >
                  <path d="M12 2a10 10 0 0 0-10 10c0 5.52 4.48 10 10 10s10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm0-14a6 6 0 0 0-6 6c0 3.31 2.69 6 6 6s6-2.69 6-6-2.69-6-6-6zm0 10c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4z" />
                </svg>
              }
              title="ورژن برنامه"
            />
          );
        },
      },
      {
        menu: "تخصص",
        link: "/expertise",
        subshow: false,
        submenu: [],
        icon(pathnamin) {
          return (
            <Tooltip
              svgIcon={
                <svg
                  className={`w-6 h-6 transition-colors duration-300 ${
                    this.subshow || pathnamin === this.link
                      ? "fill-neutral-100"
                      : "fill-gray-300 group-hover:fill-neutral-100"
                  }`}
                  xmlns="http://www.w3.org/2000/svg"
                  viewBox="0 0 24 24"
                >
                  <path d="M12 2a10 10 0 0 0-10 10c0 5.52 4.48 10 10 10s10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1h-6v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z" />
                </svg>
              }
              title="تخصص"
            />
          );
        },
      },
      {
        menu: "قوانین مقررات",
        link: "/terms",
        subshow: false,
        submenu: [],
        icon(pathnamin) {
          return (
            <Tooltip
              svgIcon={
                <ShopIcon
                  className={`w-6 h-6 transition-colors duration-300 ${
                    this.subshow || pathnamin === this.link
                      ? "fill-neutral-100"
                      : "fill-gray-300 group-hover:neutral-100"
                  }`}
                />
              }
              title="قوانین مقررات"
            />
          );
        },
      },
      {
        menu: "خروج",
        subshow: false,
        link: "#",
        submenu: [],
        icon(pathnamin) {
          return (
            <Tooltip
              svgIcon={
                <button className="flex items-center group outline-none">
                  <svg
                    className={`w-6 h-6 transition-colors duration-300 ${
                      this.subshow || pathnamin.includes(this.link)
                        ? "fill-neutral-100"
                        : "fill-gray-300 group-hover:fill-neutral-100"
                    }`}
                    xmlns="http://www.w3.org/2000/svg"
                    width="24"
                    height="24"
                    fill="none"
                    viewBox="0 0 24 24"
                  >
                    <path d="M17.44 15.87c-.19 0-.38-.07-.53-.22a.754.754 0 010-1.06l2.03-2.03-2.03-2.03a.754.754 0 010-1.06c.29-.29.77-.29 1.06 0l2.56 2.56c.29.29.29.77 0 1.06l-2.56 2.56c-.15.15-.34.22-.53.22z" />
                    <path d="M19.93 13.31H9.76c-.41 0-.75-.34-.75-.75s.34-.75.75-.75h10.17c.41 0 .75.34.75.75s-.34.75-.75.75z" />
                    <path d="M11.76 21.25c-5.15 0-8.75-3.6-8.75-8.75s3.6-8.75 8.75-8.75c.41 0 .75.34.75.75s-.34.75-.75.75c-4.27 0-7.25 2.98-7.25 7.25s2.98 7.25 7.25 7.25c.41 0 .75.34.75.75s-.34.75-.75.75z" />
                  </svg>
                </button>
              }
              title="خروج"
            />
          );
        },
      },
    ]);
  }, []);

  useEffect(() => {
    let indexOfItem = 0;
    for (let item of items) {
      indexOfItem++;
      for (let submenu of item.submenu) {
        if (pathname.replace("/", "").includes(submenu?.link.replace("/", ""))) {
          setItems((prev) =>
            prev.map((sidebarItem, i) =>
              i === indexOfItem - 1
                ? { ...sidebarItem, subshow: true }
                : sidebarItem
            )
          );
          return;
        }
      }
    }
  }, [pathname, items]);

  const navigateToMenu = (item) => {
    navigate(item?.link);
    setItems((prev) =>
      prev.map((sidebarItem) => ({ ...sidebarItem, subshow: false }))
    );
  };

  const showSubMenu = (index) => {
    setItems((prev) =>
      prev.map((sidebarItem, i) =>
        i === index
          ? { ...sidebarItem, subshow: !sidebarItem.subshow }
          : { ...sidebarItem, subshow: false }
      )
    );
  };

  const handleLogOut = () => {
    localStorage.clear();
    document.getElementById("to_login").click();
  };

  function refreshPage() {
    setTimeout(() => {
      window.location.reload(false);
    }, 1000);
  }

  const toggleSidebar = () => {
    setIsCollapsed(!isCollapsed);
  };

  return (
    <div
      className={`fixed top-0 z-[9999] h-screen bg-gradient-to-b from-gray-800 to-gray-900 text-white font-sans overflow-y-auto scrollbar-hidden flex flex-col p-4 pt-12 shadow-2xl transition-all duration-300 ${
        isCollapsed ? "w-16" : "w-64"
      }`}
    >
    
      <Link to="/login" id="to_login" onClick={refreshPage} className="hidden" />
      <div className="flex-1">
        {items.map((item, index) => (
          <div key={index} className=" mt-4">
            {item.submenu.length === 0 ? (
              <button
                onClick={() => {
                  if (item.menu === "خروج") {
                    handleLogOut();
                  } else {
                    navigateToMenu(item);
                  }
                }}
                className={`flex items-center w-full p-2 rounded-xl transition-all duration-300 group relative ${
                  pathname.replace("/", "").includes(item.link.replace("/", ""))
                    ? "bg-gray-500/80 text-white backdrop-blur-sm shadow-md"
                    : "hover:bg-gray-700/80 hover:backdrop-blur-sm hover:shadow-md"
                }`}
              >
                <div className={`flex items-center ${isCollapsed ? "justify-center" : "space-x-3"}`}>
                  {item.icon(pathname)}
                  {!isCollapsed && (
                    <span
                      className={`text-sm font-medium transition-colors duration-300 ${
                        pathname.replace("/", "").includes(item.link.replace("/", ""))
                          ? "text-white"
                          : "text-gray-200 group-hover:text-white"
                      }`}
                    >
                      {item.menu}
                    </span>
                  )}
                </div>
              </button>
            ) : (
              <button
                onClick={() => showSubMenu(index)}
                className={`flex items-center w-full p-3 rounded-xl transition-all duration-300 group relative ${
                  item.subshow
                    ? "bg-teal-600/80 text-white backdrop-blur-sm shadow-md"
                    : "hover:bg-teal-700/80 hover:backdrop-blur-sm hover:shadow-md"
                }`}
              >
                <div className={`flex items-center ${isCollapsed ? "justify-center" : "space-x-3"}`}>
                  {item.icon(pathname)}
                  {!isCollapsed && (
                    <span
                      className={`text-sm font-medium transition-colors duration-300 ${
                        item.subshow ? "text-white" : "text-gray-200 group-hover:text-white"
                      }`}
                    >
                      {item.menu}
                    </span>
                  )}
                </div>
                {!isCollapsed && item.submenu.length > 0 && (
                  <svg
                    className={`w-4 h-4 mr-auto transition-transform duration-300 ${
                      item.subshow ? "rotate-180" : ""
                    }`}
                    xmlns="http://www.w3.org/2000/svg"
                    viewBox="0 0 24 24"
                    fill="currentColor"
                  >
                    <path d="M7 10l5 5 5-5H7z" />
                  </svg>
                )}
              </button>
            )}
            {!isCollapsed && (
              <div
                className={`ml-4 transition-all duration-300 ease-in-out ${
                  item.subshow ? "max-h-[800px] opacity-100" : "max-h-0 opacity-0 overflow-hidden"
                }`}
              >
                {item.submenu.map((submenuItem, subIndex) => {
                  const isActive = pathname
                    .replace("/", "")
                    .includes(submenuItem.link.replace("/", ""));
                  return (
                    <Link
                      key={subIndex}
                      to={submenuItem.link}
                      className={`flex items-center p-2  rounded-lg transition-all duration-200 text-sm ${
                        isActive
                          ? "bg-neutral-100/80 text-white backdrop-blur-sm"
                          : "text-gray-300 hover:bg-neutral-100/80 hover:text-white hover:backdrop-blur-sm"
                      }`}
                    >
                      {submenuItem.menu}
                    </Link>
                  );
                })}
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
};

export default Sidebar;