import React, { ReactElement } from 'react';
import { ActionSubitem } from '../ActionControl/ActionSubItemProps';
import { ActionControl } from '../ActionControl/ActionControl';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { useSelector } from '../../useSelector';
import { cairoPageCtaClicked } from '@wix/bex-core/bi';
import { usePageButtonBiParams } from '../usePageButtonBiParams';
import { useIsMobile } from '../../hooks/useIsMobile';

export type SecondaryActionsElement = ReactElement<
  ActionSubitem,
  typeof SecondaryActions
>;

export function SecondaryActions({ subItems, ...props }: ActionSubitem) {
  const { initTask, reportBi } = useWixPatternsContainer();
  useSelector(() => initTask.status);

  const subItemsGrouped = subItems
    ? Array.isArray(subItems?.[0])
      ? (subItems as ActionSubitem[][])
      : [subItems as ActionSubitem[]]
    : subItems;

  const { pageType, location } = usePageButtonBiParams();
  const isMobile = useIsMobile();
  return (
    <ActionControl
      priority="secondary"
      size={isMobile ? 'small' : undefined}
      onPopoverClick={() => {
        reportBi(
          cairoPageCtaClicked({
            location,
            pageType,
            ctaName: props.biName ?? '',
            ctaType: 'secondary page dropdown',
            additionalInfo: props.biAdditionalInfo,
          }),
        );
      }}
      actionItem={{
        dataHook: 'secondary-actions',
        ...props,
        subItems: subItemsGrouped?.map((subItems) =>
          subItems?.map((subItem) => ({
            ...subItem,
            onClick: () => {
              reportBi(
                cairoPageCtaClicked({
                  location,
                  pageType,
                  ctaName: subItem.biName ?? '',
                  ctaType: 'secondary page option',
                  additionalInfo: subItem.biAdditionalInfo,
                }),
              );
              subItem.onClick?.();
            },
          })),
        ),
        onClick: () => {
          reportBi(
            cairoPageCtaClicked({
              location,
              pageType,
              ctaName: props.biName ?? '',
              ctaType: 'secondary page button',
              additionalInfo: props.biAdditionalInfo,
            }),
          );
          props.onClick?.();
        },
      }}
    />
  );
}
