import { useState, useEffect, useContext } from "react";
import { useDispatch } from "react-redux";
import { SidebarContext } from "../../../contexts/SidebarContext";
import {
  BACKDROP_HIDE,
  BACKDROP_SHOW,
} from "../../../lib/redux/slices/appSlice";

export const useSidebarState = () => {
  const [open, setOpen] = useState(false);
  const [expandedItems, setExpandedItems] = useState([]);
  const [openSub, setOpenSub] = useState({
    province: false,
    adminx: false,
    slaughter: false,
    avicuture: false,
    city: false,
    provinceFinancial: false,
    inspector: false,
    slaughterVet: false,
    superAdmin: false,
  });
  const [sidebarMobileState, setSidebarMobileState] =
    useContext(SidebarContext);
  const dispatch = useDispatch();

  const closeSidebar = () => {
    setSidebarMobileState(false);
    setOpen(false);
  };

  const handleAccordionChange = (index) => {
    setExpandedItems((prev) => {
      const newExpandedItems = [...prev];
      const currentIndex = newExpandedItems.indexOf(index);
      if (currentIndex === -1) {
        newExpandedItems.push(index);
      } else {
        newExpandedItems.splice(currentIndex, 1);
      }
      return newExpandedItems;
    });
  };

  const toggleSubMenu = (key) => {
    setOpenSub((prev) => ({
      ...prev,
      [key]: !prev[key],
    }));
  };

  useEffect(() => {
    setOpen(sidebarMobileState);
  }, [sidebarMobileState]);

  useEffect(() => {
    if (open) {
      dispatch(BACKDROP_SHOW());
    } else {
      dispatch(BACKDROP_HIDE());
    }
  }, [open, dispatch]);

  useEffect(() => {
    const handleDocumentClick = (e) => {
      if (open && !e.target.closest("#sidebar")) {
        closeSidebar();
      }
    };

    document.addEventListener("click", handleDocumentClick);
    return () => {
      document.removeEventListener("click", handleDocumentClick);
    };
  }, [open]);

  return {
    open,
    setOpen,
    expandedItems,
    openSub,
    closeSidebar,
    handleAccordionChange,
    toggleSubMenu,
  };
};
