import { observer } from 'mobx-react-lite';
import React, { useMemo } from 'react';
import {
  DropdownBase,
  IconButton,
  listItemSelectBuilder,
  SegmentedToggle,
  Tooltip,
} from '@wix/design-system';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { ViewType, ViewTypeState } from '../../state/ViewTypeState';
import { layoutConfig } from './layoutConfig';

export interface LayoutSwitchButtonProps {
  state: ViewTypeState;
  options: ViewType[];
}

function _LayoutSwitchButton({ state, options }: LayoutSwitchButtonProps) {
  const { translate: t, internalExperiments } = useWixPatternsContainer();
  const { viewType } = state;

  const isLayoutToggleRedesignEnabled = internalExperiments?.enabled(
    'specs.cairo.layout-toggle.redesign',
  );

  const dropdownOptions = useMemo(
    () =>
      options.map((option) =>
        listItemSelectBuilder({
          id: option,
          title: t(layoutConfig[option].translationKey),
          prefix: layoutConfig[option].icon,
          dataHook: `layout-option-${option}`,
        }),
      ),
    [t, options],
  );

  if (!isLayoutToggleRedesignEnabled) {
    return (
      <SegmentedToggle
        size="small"
        dataHook="layout-switch-toggle-button"
        selected={viewType}
        onClick={(_, value) => {
          if (state.viewType === value) {
            return;
          }
          state.changeViewType(value as ViewType);
        }}
      >
        {options.map((option) => (
          <SegmentedToggle.Icon
            key={option}
            value={option}
            dataHook={`toggle-option-${option}`}
            tooltipText={t(layoutConfig[option].translationKey)}
          >
            {layoutConfig[option].icon}
          </SegmentedToggle.Icon>
        ))}
      </SegmentedToggle>
    );
  }

  return (
    <DropdownBase
      dataHook="layout-switch-popover"
      options={dropdownOptions}
      selectedId={viewType}
      showArrow
      onSelect={(option) => {
        const selectedOption = option.id as ViewType;
        const index = options.indexOf(selectedOption);
        state.reportLayoutOptionClicked(selectedOption, index);
        if (viewType !== selectedOption) {
          state.changeViewType(selectedOption);
        }
      }}
    >
      {({ toggle }) => (
        <Tooltip content={t('cairo.table.layout.switchLayout')} size="medium">
          <IconButton
            dataHook="layout-switch-button"
            size="small"
            priority="secondary"
            aria-haspopup="menu"
            onClick={() => {
              state.reportLayoutSwitch();
              toggle();
            }}
          >
            {layoutConfig[viewType].icon}
          </IconButton>
        </Tooltip>
      )}
    </DropdownBase>
  );
}

export const LayoutSwitchButton = observer(_LayoutSwitchButton);
