import { useState, useCallback } from "@wordpress/element";

export function usePanelStates(storageKey, defaultStates = {}) {
  const getStoredPanelStates = () => {
    try {
      const saved = window.localStorage.getItem(storageKey);
      return saved ? JSON.parse(saved) : {};
    } catch (e) {
      return {};
    }
  };

  const savePanelStates = (states) => {
    try {
      window.localStorage.setItem(storageKey, JSON.stringify(states));
    } catch (e) {}
  };

  const [panelStates, setPanelStates] = useState(() => ({
    ...defaultStates,
    ...getStoredPanelStates(),
  }));

  const togglePanel = useCallback((panelKey) => {
    setPanelStates((prev) => {
      const newStates = { ...prev, [panelKey]: !prev[panelKey] };
      savePanelStates(newStates);
      return newStates;
    });
  }, []);

  const setPanel = useCallback((panelKey, value) => {
    setPanelStates((prev) => {
      const newStates = { ...prev, [panelKey]: value };
      savePanelStates(newStates);
      return newStates;
    });
  }, []);

  const setPanels = useCallback((updates) => {
    setPanelStates((prev) => {
      const newStates = { ...prev, ...updates };
      savePanelStates(newStates);
      return newStates;
    });
  }, []);

  const openPanelsExclusively = useCallback((targetPanels, closePanels = []) => {
    const targets = Array.isArray(targetPanels) ? targetPanels : [targetPanels];
    setPanelStates((prev) => {
      const newStates = { ...prev };
      closePanels.forEach((panel) => {
        newStates[panel] = false;
      });
      targets.forEach((panel) => {
        newStates[panel] = true;
      });
      savePanelStates(newStates);
      return newStates;
    });
  }, []);

  return {
    panelStates,
    togglePanel,
    setPanel,
    setPanels,
    openPanelsExclusively,
  };
}

export default usePanelStates;
