import React, { useState, useEffect } from "react";
import {
  FiHome,
  FiBox,
  FiUsers,
  FiShoppingCart,
  FiLogOut,
  FiX,
  FiChevronDown,
  FiChevronUp,
} from "react-icons/fi";
import { Link } from "react-router-dom";
import { useLocation, useNavigate } from "react-router-dom";
import ConfirmModal from "../common/ConfirmModal";

const Sidebar = ({
  isCollapsed,
  // toggleSidebar,
  mobileOpen,
  toggleMobileSidebar,
}) => {
  const location = useLocation();
  const navigate = useNavigate();

  // Separate dropdown states
  const [productsOpen, setProductsOpen] = useState(false);
  const [categoriesOpen, setCategoriesOpen] = useState(false);
  const [logoutOpen, setLogoutOpen] = useState(false);

  // Auto-open dropdown when route matches
  useEffect(() => {
    if (location.pathname.startsWith("/products")) setProductsOpen(true);
    if (location.pathname.startsWith("/categories")) setCategoriesOpen(true);
  }, [location.pathname]);

  const menuItems = [
    { name: "Dashboard", icon: <FiHome />, path: "/dashboard" },
    { name: "Orders", icon: <FiShoppingCart />, path: "/orders" },
    {
      name: "Products",
      icon: <FiBox />,
      subMenu: [
        { name: "Product List", path: "/products" },
        { name: "Add Product", path: "/products/add" },
      ],
      state: productsOpen,
      setState: setProductsOpen,
    },
    { name: "Users", icon: <FiUsers />, path: "/users" },
    // { name: "Report", icon: <FiUsers />, path: "/reports" },
    {
      name: "Categories",
      icon: <FiBox />,
      subMenu: [
        { name: "Category List", path: "/categories" },
        { name: "Add Category", path: "/categories/add" },
      ],
      state: categoriesOpen,
      setState: setCategoriesOpen,
    },
     { name: "Returns", icon: <FiBox />, path: "/returns" },
     { name: "Coupons", icon: <FiBox />, path: "/coupons" },
  ];

  const isActive = (path) => location.pathname === path;

  const handleLogout = () => {
    setLogoutOpen(false);
    navigate("/login");
  };

  const activeClass = `
    ${isCollapsed ? "w-12 justify-center" : "w-[193px] justify-start"}
    bg-[#4880FF] text-white rounded-[6px] h-[46px] flex items-center gap-[10px] px-4 py-[12px]
    shadow-md transition-all duration-200
  `;

  const normalClass = `
    ${isCollapsed ? "w-12 justify-center" : "w-[193px] justify-start"}
    text-gray-700 hover:bg-[#4880FF]/10 hover:text-[#4880FF] rounded-[6px] h-[46px]
    flex items-center gap-[10px] px-4 py-[12px] transition-all duration-200
  `;

  return (
    <>
      {/* Mobile overlay */}
      <div
        className={`fixed inset-0 bg-black/40 z-40 md:hidden transition-opacity ${
          mobileOpen ? "opacity-100 visible" : "opacity-0 invisible"
        }`}
        onClick={toggleMobileSidebar}
      ></div>

      {/* Sidebar */}
      <div
        className={`fixed inset-y-0 left-0 z-50 bg-white shadow-lg transform transition-all duration-300
          ${
            mobileOpen ? "translate-x-0" : "-translate-x-full"
          } md:translate-x-0 md:static
          ${isCollapsed ? "w-20" : "w-64"} flex flex-col justify-between
        `}
      >
        {/* Logo & Hamburger */}
        <div className="flex items-center m-3 px-4 py-4 border-gray-200">
          <h2
            className={`absolute left-1/2 -translate-x-1/2 font-bold text-xl text-[#4880FF] ${
              isCollapsed ? "hidden" : "block"
            }`}
          >
            Vaishnavi
          </h2>

          <div className="flex items-center gap-2">
            <button
              className="md:hidden p-2 rounded-md hover:bg-gray-100 transition"
              onClick={toggleMobileSidebar}
            >
              <FiX className="text-[#4880FF]" />
            </button>
          </div>
        </div>

        {/* Menu */}
        <nav className="mt-2 flex-1 px-2 space-y-2 flex flex-col items-center">
          {menuItems.map((item, index) => {
            if (item.subMenu) {
              const parentActive = item.subMenu.some((sub) =>
                isActive(sub.path)
              );

              return (
                <div key={index}>
                  <button
                    className={`flex items-center justify-between px-4 py-[12px] rounded-[6px] transition-all duration-200
                      ${isCollapsed ? "w-12" : "w-[193px]"}
                      ${
                        item.state || parentActive
                          ? "bg-[#4880FF] text-white shadow-md"
                          : "text-gray-700 hover:bg-[#4880FF]/10 hover:text-[#4880FF]"
                      }
                    `}
                    onClick={() => item.setState(!item.state)}
                  >
                    <div className="flex items-center gap-[10px]">
                      {item.icon}
                      <span
                        className={`${
                          isCollapsed ? "hidden" : "block font-medium"
                        }`}
                      >
                        {item.name}
                      </span>
                    </div>
                    {!isCollapsed &&
                      (item.state ? <FiChevronUp /> : <FiChevronDown />)}
                  </button>

                  {/* Submenu */}
                  {item.state && !isCollapsed && (
                    <div className="ml-6 mt-2 flex flex-col gap-2">
                      {/* {item.subMenu.map((sub) => (
                        <Link
                          to={sub.path}
                          className={
                            isActive(sub.path) ? activeClass : normalClass
                          }
                        >
                          {sub.name}
                        </Link>
                      ))} */}
                      {item.subMenu.map((sub) => (
                        <Link
                          key={sub.id} // 👈 ADD THIS
                          to={sub.path}
                          className={
                            isActive(sub.path) ? activeClass : normalClass
                          }
                        >
                          {sub.name}
                        </Link>
                      ))}
                    </div>
                  )}
                </div>
              );
            }

            return (
              <Link
                key={index}
                to={item.path}
                className={isActive(item.path) ? activeClass : normalClass}
              >
                {item.icon}
                <span
                  className={`${isCollapsed ? "hidden" : "block font-medium"}`}
                >
                  {item.name}
                </span>
              </Link>
            );
          })}
        </nav>

        {/* Logout */}
        <div className="px-4 mb-6 flex justify-center">
          <button
            className={`flex items-center justify-center gap-[10px]
              ${isCollapsed ? "w-12" : "w-[193px]"}
              h-[46px] px-4 py-[12px] rounded-[6px]
              bg-red-100 text-red-600 hover:bg-red-200 transition-all`}
            onClick={() => setLogoutOpen(true)}
          >
            <FiLogOut />
            {!isCollapsed && <span className="font-medium">Logout</span>}
          </button>
        </div>
      </div>

      {/* Confirm Modal */}
      <ConfirmModal
        isOpen={logoutOpen}
        title="Logout"
        message="Are you sure you want to logout?"
        onCancel={() => setLogoutOpen(false)}
        onConfirm={handleLogout}
      />
    </>
  );
};

export default Sidebar;
