import { useContext, useEffect } from '@wordpress/element';
import { DesignContext } from '@components/DesignPanel/DesignStore';
import { ButtonToggleGroup } from '@components/ui/ButtonToggle';
import { useStore } from 'zustand';
import { ControlsProps } from '@components/DesignPanel/types';
import ControlModifier from '@components/DesignPanel/ControlModifier';

import StrategiesPanel from '@components/DesignPanel/StrategiesPanel';
import InteractionPanel from '@components/DesignPanel/InteractionPanel';

/*
  Renders the control panel
  and shows the active modifier or expanded modifiers
*/

export const ControlPanel: React.FC<ControlsProps> = ({ controls }) => {
  const store = useContext(DesignContext);
  const { currentControl, setCurrentControl } = useStore(store);

  // set first control active
  useEffect(() => {
    if (controls.length > 0) {
      setCurrentControl(controls[0]);
    }
  }, [controls]);

  return (
    <div
      data-id="blockbite-controlPanel"
      className="flex min-h-[160px] flex-col"
    >
      <ButtonToggleGroup
        onPressedChange={(value) => {
          // dont allow toggle
          if (value !== '') {
            const control = controls.find((control) => control.id === value);
            setCurrentControl(control);
          }
        }}
        defaultPressed={currentControl?.id || ''}
        // show tabs if there are less than 4 controls
        tabs={controls.length < 4}
        size="small"
        options={controls.map((control) => ({
          value: control.id,
          label: control.label,
          icon: control?.icon,
        }))}
        className="mb-4"
      ></ButtonToggleGroup>
      {currentControl && currentControl.modifiers && (
        <>
          <ControlModifier key={currentControl.id} control={currentControl} />
          <StrategiesPanel />
          <InteractionPanel />
        </>
      )}
    </div>
  );
};

export default ControlPanel;
