import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import PropTypes from "prop-types";
import {
  Sidebar as ProSidebar,
  Menu,
  MenuItem,
  SubMenu,
} from "react-pro-sidebar";
import { FaChevronLeft, FaChevronRight, FaDatabase, FaExclamationCircle, FaCircle } from "react-icons/fa";
import { fetchMenuItems, getSubmenuItems } from "../../APIServices/MenuMaintenanceAPI";
import "../Sidebar/Sidebar.css";

const Sidebar = (props) => {
  const [collapsed, setCollapsed] = useState(true);
  const [menuItems, setMenuItems] = useState([]);
  const [subMenuItems, setSubMenuItems] = useState({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const navigate = useNavigate();

  useEffect(() => {
    const loadMenuData = async () => {
      try {
        const mainMenuItems = await fetchMenuItems();
        setMenuItems(mainMenuItems);
        
        const subMenuPromises = mainMenuItems.map(item => 
          getSubmenuItems(item.menuItemId)
            .then(subItems => subItems || [])
            .catch(() => [])
        );
        
        const subMenus = await Promise.all(subMenuPromises);
        const subMenuMap = {};
        mainMenuItems.forEach((item, index) => {
          subMenuMap[item.menuItemId] = subMenus[index];
        });
        setSubMenuItems(subMenuMap);
      } catch (err) {
        console.error("Failed to load menu data:", err);
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };
    loadMenuData();
  }, []);

  const toggleSidebar = () => {
    setCollapsed(!collapsed);
    props.onSidebarToggle?.(!collapsed);
  };

  const validatePath = (path) => {
    if (!path || path === "#" || path === "null" || path === "undefined") {
      return false;
    }
    return true;
  };

  const safeNavigate = (path) => {
    if (!validatePath(path)) {
      navigate("/admin/error404");
      return;
    }

    // Ensure path starts with /admin/
    const adminPath = path.startsWith("/admin/") ? path : `/admin/${path.replace(/^\//, '')}`;
    
    try {
      navigate(adminPath);
    } catch (error) {
      console.error(`Navigation failed:`, error);
      navigate("/admin/error404");
    }
  };

  const getIconComponent = (iconName) => {
    switch (iconName) {
      case "fa-database": return <FaDatabase />;
      case "fa-exclamation-circle": return <FaExclamationCircle />;
      default: return <FaCircle />;
    }
  };

  if (loading) return <div className="sidebar-wrapper">Loading...</div>;
  if (error) return <div className="sidebar-wrapper">Error: {error}</div>;

  return (
    <div className="sidebar-wrapper">
      <ProSidebar
        collapsed={collapsed}
        className="app-sidebar"
        backgroundColor="#e8e8e8"
        width="220px"
        collapsedWidth="30px"
      >
        <div className="sidebar-header d-flex justify-content-end px-2 pt-2">
          <button
            className="sidebar-toggle-btn btn btn-link p-0"
            onClick={toggleSidebar}
            title={collapsed ? "Expand sidebar" : "Collapse sidebar"}
          >
            {collapsed ? <FaChevronRight /> : <FaChevronLeft />}
          </button>
        </div>

        <Menu>
          {menuItems.map((menuItem) => {
            const subItems = subMenuItems[menuItem.menuItemId] || [];
            
            if (subItems.length > 0) {
              return (
                <SubMenu 
                  key={menuItem.menuItemId}
                  label={menuItem.menuItemDesc}
                  icon={getIconComponent(menuItem.main_menu_icon_name)}
                >
                  {subItems.map((subItem) => (
                    <MenuItem 
                      key={subItem.menuItemId}
                      onClick={() => safeNavigate(subItem.main_menu_action_name)}
                    >
                      {subItem.menuItemDesc}
                    </MenuItem>
                  ))}
                </SubMenu>
              );
            }
            
            return (
              <MenuItem
                key={menuItem.menuItemId}
                icon={getIconComponent(menuItem.main_menu_icon_name)}
                onClick={() => safeNavigate(menuItem.main_menu_action_name)}
              >
                {menuItem.menuItemDesc}
              </MenuItem>
            );
          })}
        </Menu>
      </ProSidebar>
    </div>
  );
};

Sidebar.defaultProps = {
  logo: {},
};

Sidebar.propTypes = {
  logo: PropTypes.object,
  onSidebarToggle: PropTypes.func,
};

export default Sidebar;