import { useState, useEffect } from '@wordpress/element';
import { ControlsProps } from '@components/DesignPanel/types';

import ControlModifier from '@components/DesignPanel/ControlModifier';
import ButtonToggleGroup from '../ui/ButtonToggle';
import StrategiesPanel from '@components/DesignPanel/StrategiesPanel';
import InteractionPanel from '@components/DesignPanel/InteractionPanel';

/*
  Loops over multiple controls and renders the appropriate control in a flat vertical view
*/

export const ControlExpandPanel: React.FC<ControlsProps> = ({
  controls,
  filter,
}) => {
  const [filteredControls, setFilteredControls] = useState([]);
  const [currentFilterValue, setCurrentFilterValue] = useState('');

  useEffect(() => {
    if (filter && filter.length && controls.length) {
      setCurrentFilterValue(filter[0].value);
      const filtered = controls.filter((control) => {
        return filter[0].controls.includes(control.id);
      });
      setFilteredControls(filtered);
    } else {
      setFilteredControls(controls);
    }
  }, [filter, controls]);

  return (
    <div
      data-id="blockbite-controlExpandPanel"
      className="flex min-h-[160px] flex-col gap-4"
    >
      {filter && (
        <ButtonToggleGroup
          size="small"
          defaultPressed={currentFilterValue}
          options={filter}
          tabs={true}
          onPressedChange={(value) => {
            if (value !== '') {
              setCurrentFilterValue(value);
              // get index by value
              const index = filter.findIndex((f) => f.value === value);

              const filtered = controls.filter((control) => {
                return filter[index].controls.includes(control.id);
              });
              setFilteredControls(filtered);
            }
          }}
        />
      )}
      {filteredControls.map((control, index) => {
        return (
          <div key={`${control.id}-${index}`}>
            {control.modifiers && <ControlModifier control={control} />}
          </div>
        );
      })}
      <StrategiesPanel />
      <InteractionPanel />
    </div>
  );
};

export default ControlExpandPanel;
