import { Grid } from "../components/Grid/Grid";
import { checkIsMobile } from "../utils/checkIsMobile";
import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { ChevronDownIcon } from "@heroicons/react/24/solid";
import { useUserProfileStore } from "../context/zustand-store/userStore";
import { useNavigate } from "@tanstack/react-router";
import { getFaPermissions } from "../utils/getFaPermissions";
import { useSideBarStore } from "../context/zustand-store/appStore";
import SVGImage from "../components/SvgImage/SvgImage";
import { getInspectionMenuItems } from "../config/menuItems";
import {
  ChevronLeftIcon,
  ChevronRightIcon,
  MagnifyingGlassIcon,
  BuildingOfficeIcon,
  GlobeAsiaAustraliaIcon,
} from "@heroicons/react/24/outline";

const containerVariants = {
  hidden: {},
  visible: { transition: { staggerChildren: 0.03 } },
};
const itemVariants = {
  hidden: { opacity: 0, x: -20 },
  visible: {
    opacity: 1,
    x: 0,
    transition: { type: "spring" as const, stiffness: 200, damping: 25 },
  },
};
const submenuVariants = {
  hidden: { height: 0, opacity: 0 },
  visible: {
    height: "auto" as const,
    opacity: 1,
    transition: { ease: "easeInOut" as const, duration: 0.15 },
  },
  exit: {
    height: 0,
    opacity: 0,
    transition: { ease: "easeInOut" as const, duration: 0.1 },
  },
};

const sidebarVariants = {
  open: {
    width: "18rem",
    transition: {
      type: "spring" as const,
      stiffness: 500,
      damping: 30,
      duration: 0.25,
    },
  },
  closed: {
    width: "3.75rem",
    transition: {
      type: "spring" as const,
      stiffness: 500,
      damping: 30,
      duration: 0.2,
    },
  },
};

export const SideBar = () => {
  const isMobile = checkIsMobile();
  const { profile } = useUserProfileStore();
  const menuItems = getInspectionMenuItems(profile?.permissions || []);
  const [search, setSearch] = useState("");

  const { isSideBarOpen, toggleSideBar } = useSideBarStore();

  const getOpenedItem = () => {
    if (window.location.pathname !== "/") {
      const matchedIndex = menuItems.findIndex((item) =>
        item.subItems.some((sub) => sub.path === window.location.pathname),
      );
      return matchedIndex;
    } else {
      return null;
    }
  };

  const [openIndex, setOpenIndex] = useState<number | null>(getOpenedItem());

  const navigate = useNavigate();

  const filteredItems = menuItems
    .map((item) => {
      const filteredSubItems = item.subItems.filter(
        (subItem) =>
          getFaPermissions(subItem.name)
            .toLowerCase()
            .includes(search.toLowerCase()) ||
          subItem.path.toLowerCase().includes(search.toLowerCase()),
      );

      return {
        ...item,
        subItems: filteredSubItems,
      };
    })
    .filter(
      (item) =>
        item.subItems.length > 0 ||
        item.fa.toLowerCase().includes(search.toLowerCase()),
    );

  if (isMobile) return null;

  const toggleSubmenu = (index: number) => {
    setOpenIndex((prev) => (prev === index ? null : index));
  };

  return (
    <motion.div
      initial={isSideBarOpen ? "open" : "closed"}
      animate={isSideBarOpen ? "open" : "closed"}
      variants={sidebarVariants}
      className={`z-10 top-12 right-0 h-[calc(100vh-3rem)] bg-gray-50 dark:bg-dark-800 border-l border-gray-200 dark:border-dark-600 overflow-y-auto overflow-x-hidden p-4`}
    >
      <Grid className="h-full">
        <motion.div
          variants={containerVariants}
          initial="hidden"
          animate="visible"
          className={`flex flex-col ${isSideBarOpen ? "gap-2" : "gap-4"}`}
        >
          {isSideBarOpen && (
            <motion.div
              initial={{ opacity: 0, y: -10, scale: 0.95 }}
              animate={{ opacity: 1, y: 0, scale: 1 }}
              transition={{ duration: 0.25, ease: "easeOut" }}
              className="relative overflow-hidden rounded-2xl bg-white/80 dark:bg-dark-700/90 backdrop-blur-sm p-2 border border-gray-200/60 dark:border-dark-500/50 shadow-lg shadow-primary-500/5 dark:shadow-black/20"
            >
              <div className="absolute inset-0 bg-linear-to-br from-primary-500/5 via-transparent to-primary-400/5 dark:from-primary-400/10 dark:via-transparent dark:to-primary-500/10 pointer-events-none" />
              <div className="relative flex flex-col gap-3">
                <div className="flex items-center gap-3">
                  <div className="shrink-0 relative">
                    <div className="w-14 h-14 rounded-2xl bg-linear-to-br from-primary-500 via-primary-600 to-primary-700 dark:from-primary-400 dark:via-primary-500 dark:to-primary-600 flex items-center justify-center shadow-lg shadow-primary-500/30 dark:shadow-primary-400/20 ring-2 ring-white/50 dark:ring-dark-600/50">
                      <span className="text-white font-bold text-base tracking-tight">
                        {profile?.user?.first_name?.[0] ||
                          profile?.fullname?.[0] ||
                          ""}
                        {profile?.user?.last_name?.[0] || ""}
                      </span>
                    </div>
                    <div className="absolute -bottom-0.5 -right-0.5 w-4 h-4 bg-green-500 dark:bg-green-400 rounded-full border-2 border-white dark:border-dark-700 shadow-sm" />
                  </div>
                  <div className="flex-1 min-w-0 space-y-1.5">
                    <h3 className="text-[15px] font-bold text-gray-900 dark:text-white truncate leading-tight">
                      {profile?.user?.first_name || profile?.fullname || ""}{" "}
                      {profile?.user?.last_name || ""}
                    </h3>
                    {(() => {
                      const permissions = profile?.permissions || [];
                      const hasAdmin =
                        Array.isArray(permissions) &&
                        permissions.includes("admin");

                      if (hasAdmin) {
                        return (
                          <div className="flex items-center gap-2">
                            <div className="flex items-center justify-center w-5 h-5 rounded-md bg-primary-100/80 dark:bg-primary-500/20">
                              <BuildingOfficeIcon className="w-3 h-3 text-primary-600 dark:text-primary-400 shrink-0" />
                            </div>
                            <span className="text-xs font-semibold text-gray-700 dark:text-gray-200 truncate">
                              بازرس ارشد
                            </span>
                          </div>
                        );
                      }

                      if (profile?.role?.role_name) {
                        return (
                          <div className="flex items-center gap-2">
                            <div className="flex items-center justify-center w-5 h-5 rounded-md bg-primary-100/80 dark:bg-primary-500/20">
                              <BuildingOfficeIcon className="w-3 h-3 text-primary-600 dark:text-primary-400 shrink-0" />
                            </div>
                            <span className="text-xs font-semibold text-gray-700 dark:text-gray-200 truncate">
                              {profile?.organization?.name ||
                                profile?.role?.role_name}
                            </span>
                          </div>
                        );
                      }

                      return null;
                    })()}
                  </div>
                </div>
                {isSideBarOpen && (
                  <motion.button
                    onClick={() => navigate({ to: "/" })}
                    whileTap={{ scale: 0.97 }}
                    className="w-full flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl bg-primary-500 hover:bg-primary-600 cursor-pointer dark:bg-primary-800 dark:hover:bg-primary-700 text-white font-semibold text-sm transition-all duration-200 shadow-md hover:shadow-lg"
                  >
                    <GlobeAsiaAustraliaIcon className="w-5 h-5" />
                    <span>مشاهده نقشه</span>
                  </motion.button>
                )}
              </div>
            </motion.div>
          )}
          <div className="flex gap-1 items-center">
            {isSideBarOpen && (
              <div className="relative w-full">
                <input
                  type="text"
                  placeholder="جستجو..."
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  className="w-full pl-10 pr-4 py-1 rounded-lg  dark:border-dark-600 bg-white border-[0.5px] border-gray-300 dark:bg-dark-700 text-sm text-gray-600 dark:text-gray-100 placeholder:text-gray-400 focus:outline-none focus:ring-1 focus:ring-primary-500"
                />
                <MagnifyingGlassIcon className="w-5 h-5 text-gray-400 dark:text-dark-300 absolute left-3 top-[15%] pointer-events-none" />
              </div>
            )}
            <button
              className="p-2 rounded-full cursor-pointer"
              onClick={() => {
                toggleSideBar({ state: !isSideBarOpen });
              }}
            >
              {isSideBarOpen ? (
                <ChevronRightIcon className="h-6 w-6 text-gray-500 dark:text-primary-100" />
              ) : (
                <ChevronLeftIcon className="h-6 w-6 text-gray-500 dark:text-primary-100" />
              )}
            </button>
          </div>

          {filteredItems
            ?.filter((s) => s.subItems)
            .map(({ fa, icon: Icon, subItems }, index) => (
              <motion.div key={index} variants={itemVariants}>
                <motion.button
                  onClick={() => {
                    toggleSideBar({ state: true });
                    toggleSubmenu(index);
                  }}
                  whileTap={{ scale: 0.97 }}
                  className={`w-full flex justify-between items-center transition-all border-gray-200 dark:border-dark-600 cursor-pointer text-gray-600 dark:text-primary-100 ${
                    isSideBarOpen &&
                    `px-4 py-2 rounded-xl text-right  text-dark-800 dark:text-dark-100 border hover:shadow-sm  ${
                      isSideBarOpen && openIndex === index
                        ? "bg-primary-50 dark:bg-dark-500"
                        : "bg-white dark:bg-dark-700"
                    }`
                  }`}
                >
                  <div className="flex items-center gap-3">
                    <SVGImage
                      src={Icon}
                      className={` text-gray-600 dark:text-primary-100 ${
                        !isSideBarOpen && "cursor-pointer"
                      }`}
                    />
                    {isSideBarOpen && (
                      <span className=" text-gray-600 dark:text-primary-100 font-semibold">
                        {fa}
                      </span>
                    )}
                  </div>
                  {isSideBarOpen && (
                    <ChevronDownIcon
                      className={`w-5 h-5 text-gray-600 dark:text-gray-300 transition-transform duration-300 ${
                        openIndex === index ? "rotate-180" : ""
                      }`}
                    />
                  )}
                </motion.button>

                <AnimatePresence>
                  {openIndex === index && isSideBarOpen && (
                    <motion.div
                      key="submenu"
                      variants={submenuVariants}
                      initial="hidden"
                      animate="visible"
                      exit="exit"
                      className="mt-2 mr-2 flex flex-col gap-2 border-r-2 border-primary-500 dark:border-primary-400 pr-4"
                    >
                      {subItems
                        .filter((item) => !item?.path.includes("$"))
                        ?.map((sub, subIndex) => (
                          <motion.button
                            onClick={() => {
                              navigate({ to: sub.path });
                            }}
                            key={subIndex}
                            whileTap={{ scale: 0.97 }}
                            className={`${
                              location.pathname === sub.path
                                ? "bg-primary-100 dark:bg-dark-500 hover:bg-primary-100 dark:hover:bg-dark-400"
                                : "bg-white dark:bg-dark-600 hover:bg-primary-100 dark:hover:bg-dark-700"
                            } text-nowrap text-gray-600 text-sm dark:text-dark-200 px-3 py-2 rounded-lg text-right transition-colors shadow-sm cursor-pointer`}
                          >
                            {getFaPermissions(sub.name)}
                          </motion.button>
                        ))}
                    </motion.div>
                  )}
                </AnimatePresence>
              </motion.div>
            ))}
        </motion.div>
      </Grid>
    </motion.div>
  );
};
