import {
  useState,
  useEffect,
  Suspense,
  lazy,
  useMemo,
} from '@wordpress/element';
import { ModifierPanelProps } from '@components/DesignPanel/types';
import { ChapterDivider } from '@components/ui/ChapterDivider';

import ButtonToggleGroup from '@components/ui/ButtonToggle';
import TailwindIcon from 'blockbite-icons/dist/Tailwind';
import Half3Icon from 'blockbite-icons/dist/Half3';

export const ThemeOrNative: React.FC<ModifierPanelProps> = ({
  currentControlId,
  currentControlLabel,
  modifiers,
  emitOptions,
}) => {
  const [category, setCategory] = useState<string>('theme');
  const [activeControl, setActiveControl] = useState<string | null>(null);
  const [codexValue, setCodexValue] = useState<any>(null);
  const [currentModifier, setCurrentModifier] = useState<any>();

  // Set the first modifier on mount
  useEffect(() => {
    setCurrentModifier(modifiers[0]);
  }, []);

  // Update activeControl and codexValue when category or currentModifier changes
  useEffect(() => {
    if (currentModifier?.id) {
      const dynamicSplit = currentModifier.dynamicControl?.split('|') || [];
      const codexSplit = currentModifier.codex?.split('|') || [];

      if (dynamicSplit.length > 0 && codexSplit.length > 0) {
        setActiveControl(dynamicSplit[category === 'theme' ? 0 : 1] || null);
        setCodexValue(codexSplit[category === 'theme' ? 0 : 1] || null);
      }
    }
  }, [category, currentModifier?.id]);

  // Lazy load the dynamic component
  const DynamicComponent = useMemo(() => {
    return activeControl
      ? lazy(
          () =>
            import(`@components/DesignPanel/DynamicControls/${activeControl}`)
        )
      : null;
  }, [activeControl]);

  return (
    <div key={currentControlId}>
      <div>
        <ChapterDivider title={currentControlLabel} />
        {modifiers.length > 1 && (
          <ButtonToggleGroup
            defaultPressed={currentModifier?.id}
            onPressedChange={(value) => {
              if (value) {
                const selectedModifier = modifiers.find(
                  (modifier) => modifier.id === value
                );
                if (selectedModifier) {
                  setCurrentModifier(selectedModifier);
                }
              }
            }}
            display="icon"
            size="small"
            tabs={modifiers.length < 4}
            options={modifiers.map((modifier) => ({
              label: modifier.label,
              value: modifier.id,
              icon: modifier.icon,
            }))}
            className="mb-4"
          />
        )}
      </div>

      <ButtonToggleGroup
        size="small"
        display="icon"
        defaultPressed="theme"
        className="mb-4"
        options={[
          {
            label: 'theme',
            value: 'theme',
            icon: Half3Icon,
          },
          {
            label: 'native',
            value: 'native',
            icon: TailwindIcon,
          },
        ]}
        onPressedChange={(value) => {
          setCategory(value);
        }}
      />

      {DynamicComponent && (
        <Suspense key={`${category}-${activeControl}`}>
          <DynamicComponent
            activeOptionValue={currentModifier?.activeOptionValue || null} // Ensure these props exist
            options={category === 'theme' ? [] : currentModifier?.options}
            codex={codexValue}
            emitOptions={emitOptions}
            modifierId={currentModifier?.id}
          />
        </Suspense>
      )}
    </div>
  );
};

export default ThemeOrNative;
