import { useState } from '@wordpress/element';
import { interactionPanel } from '@tailwind/interaction';
import {
  Button,
  ButtonGroup,
  Notice,
  TextControl,
  ToggleControl,
} from '@wordpress/components';

const InteractionControlSettings = (props: any) => {
  const panelOptions =
    interactionPanel?.controls?.[0]?.modifiers?.[0]?.options || [];
  const { attributes, setAttributes } = props;
  const { biteMeta } = attributes;
  const currentActionType = biteMeta?.interaction?.actionType || '';
  const currentActionRef = biteMeta?.interaction?.actionRef || '';
  const [previewOn, setPreviewOn] = useState(false);

  interface applyDesignProps {
    actionType?: string;
    actionRef?: string;
  }

  const addPreview = () => {
    const currentBlock = document.querySelector(
      `[data-block="${props.clientId}"]`
    );
    const refBlocks = currentActionRef
      ? [...document.querySelectorAll(`.${currentActionRef}`)]
      : [];

    currentBlock?.classList.add('b_active');
    refBlocks.forEach((block) => {
      block.classList.add('b_active');
    });

    setPreviewOn(true);
  };

  const removePreview = () => {
    const currentBlock = document.querySelector(
      `[data-block="${props.clientId}"]`
    );
    const refBlocks = currentActionRef
      ? [...document.querySelectorAll(`.${currentActionRef}`)]
      : [];

    currentBlock?.classList.remove('b_active');
    refBlocks.forEach((block) => {
      block.classList.remove('b_active');
    });

    setPreviewOn(false);
  };

  const togglePreview = () => {
    if (previewOn) {
      removePreview();
    } else {
      addPreview();
    }
  };

  const applyDesign = ({ actionType, actionRef }: applyDesignProps) => {
    const newInteraction = {} as applyDesignProps;

    if (actionType != null) {
      newInteraction['actionType'] = actionType;
    }

    if (actionRef) {
      newInteraction['actionRef'] = actionRef;
    }

    // Remove preview if action type is changed
    removePreview();

    setAttributes({
      biteMeta: {
        ...attributes.biteMeta,
        interaction: {
          ...attributes.biteMeta.interaction,
          ...newInteraction,
        },
      },
    });
  };

  return (
    panelOptions.length && (
      <>
        <div className="flex w-full items-center justify-between">
          <ButtonGroup>
            {panelOptions.map((o) => (
              <Button
                key={o.value}
                variant={
                  o.value === currentActionType ? 'primary' : 'secondary'
                }
                size="small"
                onClick={() => {
                  applyDesign({
                    actionType: o.value,
                  });
                }}
              >
                {o.label}
              </Button>
            ))}
          </ButtonGroup>
          <ToggleControl
            checked={previewOn}
            label="Preview"
            onChange={togglePreview}
            className="!mb-0"
          />
        </div>
        <TextControl
          help="Also activate elements with this class name (optional)"
          label="Action Reference"
          onChange={(value) => {
            applyDesign({
              actionRef: value,
            });
          }}
          value={currentActionRef}
        />
      </>
    )
  );
};

export const InteractionControl = (props: any) => {
  return (
    <div className="flex flex-col space-y-4 pt-4">
      <Notice status="info" isDismissible={false}>
        <p>
          Please save and open the page to view the hover/click interactions in
          action.
        </p>
      </Notice>
      <InteractionControlSettings {...props} />
    </div>
  );
};
