import { useState } from '@wordpress/element';
import { BlockControls } from '@wordpress/block-editor';
import { Popover, TabPanel, ToolbarButton } from '@wordpress/components';
import Half3Icon from 'blockbite-icons/dist/Half3';

import { StyleInspectorClasses } from './StyleInspectorClasses';
import { StyleInspectorPresets } from './StyleInspectorPresets';

export const StyleInspector = (props: any) => {
  const {
    attributes,
    handleStyleInspectorOpen,
    name: blockname,
    setAttributes,
  } = props;
  const [isVisible, setIsVisible] = useState(false);

  return (
    <BlockControls group="other">
      <ToolbarButton
        icon={<Half3Icon width="20" height="20" />}
        label="Inspect Blockbite styles and presets"
        onClick={() => {
          setIsVisible((prev) => {
            if (!prev) {
              handleStyleInspectorOpen();
            }
            return !prev;
          });
        }}
      >
        {isVisible && (
          <Popover
            variant="toolbar"
            onClose={() => {
              // Timeout required for allowing the ToolbarButton to toggle the popover without interference
              setTimeout(() => setIsVisible(false), 100);
            }}
            onClick={(e) => e.stopPropagation()}
          >
            <TabPanel
              onSelect={function noRefCheck() {}}
              tabs={[
                {
                  name: 'styles',
                  title: 'Bite Styles',
                },
                {
                  name: 'presets',
                  title: 'Bite Presets',
                },
              ]}
              children={(tab) => {
                switch (tab.name) {
                  case 'styles':
                    return <StyleInspectorClasses attributes={attributes} />;
                  case 'presets':
                    return (
                      <StyleInspectorPresets
                        blockname={blockname}
                        setAttributes={setAttributes}
                      />
                    );
                  default:
                    return null;
                }
              }}
            />
          </Popover>
        )}
      </ToolbarButton>
    </BlockControls>
  );
};
