import { useContext, useEffect, useState } from '@wordpress/element';
import { ModifierPanelProps } from '@components/DesignPanel/types';
import { useStore } from 'zustand';
import { DesignContext } from '@components/DesignPanel/DesignStore';
import ButtonToggleGroup from '@components/ui/ButtonToggle';
import { useActiveOptionValue } from '@components/DesignPanel/hooks/useActiveOptionvalue';
import { ChapterDivider } from '@components/ui/ChapterDivider';

export const LayoutAlign: React.FC<ModifierPanelProps> = ({
  currentControlId,
  modifiers,
  emitOptions,
}) => {
  const [layoutXValue, setLayoutXValue] = useState('');
  const [layoutYValue, setLayoutYValue] = useState('');
  const [modifierX, setModifierX] = useState<any>({});
  const [modifierY, setModifierY] = useState<any>({});

  const store = useStore(useContext(DesignContext));

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

  const activeFlexType = useActiveOptionValue('flextype', store, true);

  useEffect(() => {
    /* keep horizontal, horizontal and vertical vertical  */
    if (
      modifiers.length === 2 &&
      activeFlexTypeDirection.includes('row') &&
      activeFlexType === 'flex'
    ) {
      setModifierX({ ...modifiers[0] });
      setModifierY({ ...modifiers[1] });
    } else if (
      modifiers.length === 2 &&
      activeFlexTypeDirection.includes('col') &&
      activeFlexType === 'flex'
    ) {
      setModifierX({ ...modifiers[1] });
      setModifierY({ ...modifiers[0] });
    } else if (activeFlexType === 'grid') {
      setModifierX({ ...modifiers[0] });
      setModifierY({ ...modifiers[1] });
    }
  }, [activeFlexTypeDirection, activeFlexType]);

  return (
    <div key={`LayoutAlign${currentControlId}`}>
      <ChapterDivider title="Layout Align" />
      {modifierX?.id && modifierY?.id && (
        <div className="flex flex-col gap-2">
          <div key="layoutX">
            <ButtonToggleGroup
              size="small"
              display="icon"
              defaultPressed={layoutXValue}
              onPressedChange={(value) => {
                console.log('layoutXValue', value);
                setLayoutXValue(value);
                emitOptions([{ id: modifierX.id, value: value }]);
              }}
              options={modifierX.options}
            />
          </div>
          <div key="layoutY">
            <ButtonToggleGroup
              size="small"
              display="icon"
              defaultPressed={layoutYValue}
              onPressedChange={(value) => {
                setLayoutYValue(value);
                emitOptions([{ id: modifierY.id, value: value }]);
              }}
              options={modifierY.options}
            />
          </div>
        </div>
      )}
    </div>
  );
};

export default LayoutAlign;
