import { useContext, useEffect, useState } from '@wordpress/element';

import { ModifierPanelProps } from '@components/DesignPanel/types';
import { useStore } from 'zustand';
import { DesignContext } from '@components/DesignPanel/DesignStore';
import { useActiveOptionValue } from '@components/DesignPanel/hooks/useActiveOptionvalue';

import ButtonToggleGroup from '@components/ui/ButtonToggle';
import { ChapterDivider } from '@components/ui/ChapterDivider';

export const LayoutDirection: React.FC<ModifierPanelProps> = ({
  currentControlId,
  modifiers,
  emitOptions,
}) => {
  const [options, setOptions] = useState<any>([]);
  const [layoutValue, setLayoutValue] = useState('');

  const store = useStore(useContext(DesignContext));

  const { currentResponsive } = store;

  const activeFlexTypeValue = useActiveOptionValue('flextype', store, true);
  const activeFlexTypeDirection = useActiveOptionValue('flexdirection', store);

  useEffect(() => {
    if (modifiers.length > 0) {
      const formatOptions = modifiers[0].options.map((option) => {
        //* for the sake of clearity, we are changing the label of the options to the user
        return {
          ...option,
          label: option.label.includes('Row')
            ? option.label.replace('Row', 'Column')
            : option.label.replace('Column', 'Row'),
        };
      });
      setOptions(formatOptions);
    }

    // set a default value for the layout direction
    if (activeFlexTypeValue === 'flex' && activeFlexTypeDirection === '') {
      const direction =
        currentResponsive == 'all' ||
        currentResponsive == 'xl' ||
        currentResponsive == '2xl'
          ? 'row'
          : 'col';
      setLayoutValue(direction);
      emitOptions([{ id: 'flexdirection', value: direction }]);
    }
  }, [activeFlexTypeValue]);

  return (
    <div key={`LayoutDirection${currentControlId}`}>
      <ChapterDivider title="Layout Direction" />
      {options && options.length > 0 && (
        <ButtonToggleGroup
          size="compact"
          display="icon"
          defaultPressed={layoutValue}
          onPressedChange={(value) => {
            setLayoutValue(value);
            emitOptions([{ id: 'flexdirection', value: value }]);
          }}
          options={options}
        />
      )}
    </div>
  );
};

export default LayoutDirection;
