// src/withInspectorControl.tsx

import { createHigherOrderComponent } from '@wordpress/compose';
import { InspectorControls } from '@wordpress/block-editor';

import { PanelBody } from '@wordpress/components';
import { Fragment, useState } from '@wordpress/element';
import { StyleControl } from './StyleControl';
import { LayoutControl } from './LayoutControl';
import { MediaControl } from './MediaControl';
import { MotionControl } from './MotionControl';

import CubeIcon from 'blockbite-icons/dist/Cube';
import LayoutIcon from 'blockbite-icons/dist/Layout';
import DimensionsIcon from 'blockbite-icons/dist/Dimensions';
import ImageIcon from 'blockbite-icons/dist/Image';
import TokenIcon from 'blockbite-icons/dist/Tokens';
import LightningBoltIcon from 'blockbite-icons/dist/LightningBolt';
import { Icon } from '@components/ui/Icon';

import { useDynamicBlockSupportHook } from '@components/Settings/BlockSupport/BlockSupportHooks';
import DynamicBlockSupport from '@components/Settings/BlockSupport/DynamicBlockSupport';
import { useBlockSupportStore } from '@components/Settings/BlockSupport/BlockSupportStore';
import {
  allowedBlockbiteBlock,
  isLayoutVisualBlock,
  useIsSelectedOrChild,
} from './ControlHelpers';

import { useDefaultPreset } from '@components/PresetPanel/useDefaultPreset';
import PresetPanel from '@components/PresetPanel/PresetPanel';
import { TabsWrapper, TabsList, TabsContent } from '@components/ui/Tabs';
import { StyleInspector } from './StyleInspector';
import { InteractionControl } from './InteractionControl';

interface WithInspectorControlProps {
  name: string;
  attributes: { [key: string]: any };
  setAttributes: (attributes: { [key: string]: any }) => void;
  isSelected: boolean;
  clientId: string;
}

export const BiteStyleControl = createHigherOrderComponent((BlockEdit: any) => {
  return (props: WithInspectorControlProps) => {
    const { name, isSelected, clientId } = props;
    const [inspectorViewTab, setInspectorViewTab] = useState('design');
    const [currentPresetId] = useState<number | null | string>(null);

    /*
     * Check if block is dynamic and if it is allowed
     */
    const blockDynamicSupport = useDynamicBlockSupportHook(name);
    const hasSupport =
      !blockDynamicSupport.is_dynamic || blockDynamicSupport.is_allowed;

    const isLayoutVisual = isLayoutVisualBlock(name);
    const isSelectedOrChild = useIsSelectedOrChild(clientId, isSelected);

    useDefaultPreset({
      props,
      isLayoutVisual,
      isSelectedOrChild,
      currentPresetId,
    });

    const handleStyleInspectorOpen = () => {
      wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block');
      setInspectorViewTab('current');
    };

    if (!allowedBlockbiteBlock(name)) {
      return (
        <Fragment>
          <BlockEdit {...props} />
        </Fragment>
      );
    } else {
      return (
        <Fragment>
          <BlockEdit {...props} />
          <StyleInspector
            {...props}
            handleStyleInspectorOpen={handleStyleInspectorOpen}
          />
          {isSelected && (
            <InspectorControls>
              <PanelBody title="Blockbite">
                <TabsWrapper>
                  <TabsList
                    className="[&_[role='tab']]:flex-grow"
                    options={[
                      ...(hasSupport
                        ? [
                            {
                              name: 'style',
                              title: 'Style',
                              icon: <Icon icon={CubeIcon} />,
                            },
                          ]
                        : []),
                      ...(isLayoutVisual.layout
                        ? [
                            {
                              name: 'layout',
                              title: 'Layout',
                              icon: <Icon icon={LayoutIcon} />,
                            },
                          ]
                        : []),
                      ...(isLayoutVisual.visual
                        ? [
                            {
                              name: 'media',
                              title: 'Media',
                              icon: <Icon icon={ImageIcon} />,
                            },
                          ]
                        : []),
                      ...(hasSupport
                        ? [
                            {
                              name: 'motion',
                              title: 'Motion',
                              icon: <Icon icon={DimensionsIcon} />,
                            },
                          ]
                        : []),
                      ...(hasSupport
                        ? [
                            {
                              name: 'library',
                              title: 'Library',
                              icon: <Icon icon={TokenIcon} />,
                            },
                          ]
                        : []),
                      ...(hasSupport
                        ? [
                            {
                              name: 'interaction',
                              title: 'Interaction',
                              icon: <Icon icon={LightningBoltIcon} />,
                            },
                          ]
                        : []),
                    ]}
                  />
                  {hasSupport && (
                    <TabsContent value="style">
                      <StyleControl
                        {...props}
                        currentTab={inspectorViewTab}
                        setCurrentTab={setInspectorViewTab}
                      />
                    </TabsContent>
                  )}
                  {isLayoutVisual.layout && (
                    <TabsContent value="layout">
                      <LayoutControl
                        {...props}
                        currentTab={inspectorViewTab}
                        setCurrentTab={setInspectorViewTab}
                      />
                    </TabsContent>
                  )}
                  {isLayoutVisual.visual && (
                    <TabsContent value="media">
                      <MediaControl
                        {...props}
                        currentTab={inspectorViewTab}
                        setCurrentTab={setInspectorViewTab}
                      />
                    </TabsContent>
                  )}
                  {hasSupport && (
                    <TabsContent value="motion">
                      <MotionControl
                        {...props}
                        currentTab={inspectorViewTab}
                        setCurrentTab={setInspectorViewTab}
                      />
                    </TabsContent>
                  )}
                  {hasSupport && (
                    <TabsContent value="library">
                      <PresetPanel {...props} />
                    </TabsContent>
                  )}
                  {hasSupport && (
                    <TabsContent value="interaction">
                      <InteractionControl {...props} />
                    </TabsContent>
                  )}
                </TabsWrapper>

                {!hasSupport && (
                  <DynamicBlockSupport
                    blockname={props.name}
                    defaultChecked={blockDynamicSupport.is_allowed}
                    updateDynamicBlocks={(dynamic_blocks) => {
                      const { setAllowedDynamic } =
                        useBlockSupportStore.getState();
                      setAllowedDynamic(dynamic_blocks);
                    }}
                  />
                )}
              </PanelBody>
            </InspectorControls>
          )}
        </Fragment>
      );
    }
  };
}, 'withInspectorControl');
