import { useContext, useState } from '@wordpress/element';
import { DesignPanelProps } from '@components/DesignPanel/types';
import PanelEditor from '@components/DesignPanel/PanelEditor';
import PanelCurrent from '@components/DesignPanel/PanelCurrent';

import useInitCurrentDesign from '@components/DesignPanel/hooks/useInitCurrentDesign';
import useEmitBiteObject from '@components/DesignPanel/hooks/useEmitBiteObject';

import { TabsWrapper, TabsContent } from '@components/ui/Tabs';

import { DesignContext } from '@components/DesignPanel/DesignStore';
import { useStore } from 'zustand';
/*
 * init
 * @param panels
 * @returns void
 * Iniates the store values creates a flat list of all modifiers and sets the current design
 */

export const DesignPanel = ({
  emitDesign,
  panels,
  defaultClass,
  defaultDesign,
  currentTab = null,
  content = null,
  setCurrentTab = null,
  showResponsivePanel = true,
}: DesignPanelProps) => {
  const store = useStore(useContext(DesignContext));
  const { setCurrentControl } = store;

  // track changens on all panels and update the current design
  useInitCurrentDesign({
    defaultDesign,
    defaultClass,
    panels,
    content,
  });

  // emit any changes to the parent component
  useEmitBiteObject({
    emitDesign,
  });

  const [panelId, setPanelId] = useState('');
  const controlledTabProps: any = {};

  if (currentTab != null && setCurrentTab != null) {
    controlledTabProps['value'] = currentTab;
    controlledTabProps['onValueChange'] = setCurrentTab;
  }

  return (
    <TabsWrapper defaultValue="design" {...controlledTabProps}>
      <TabsContent value="current">
        <PanelCurrent
          panels={panels}
          emitCurrent={(design: any) => {
            emitDesign({
              currentStyle: [...design.currentStyle],
              currentClass: design.currentClass,
            });
          }}
          setCurrentTab={setCurrentTab}
          setPanelId={setPanelId}
        />
      </TabsContent>
      <TabsContent value="design">
        <PanelEditor
          panels={panels}
          panelId={panelId}
          content={content}
          setPanelId={(d) => {
            setCurrentControl({});
            setPanelId(d);
          }}
          showResponsivePanel={showResponsivePanel}
          setCurrentTab={setCurrentTab}
        />
      </TabsContent>
    </TabsWrapper>
  );
};
export default DesignPanel;
