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

export type PrimaryActionsElement = ReactElement<
  ActionSubitem,
  typeof PrimaryActions
>;

export function PrimaryActions({ subItems, ...props }: ActionSubitem) {
  const { initTask, translate: t, reportBi } = useWixPatternsContainer();
  useSelector(() => initTask.status);
  const isMobile = useIsMobile();

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

  return (
    <ActionControl
      size={isMobile ? 'small' : undefined}
      fullWidth={isMobile}
      onPopoverClick={() => {
        reportBi(
          cairoPageCtaClicked({
            location: 'Collection Page Header',
            pageType: 'Collection',
            ctaName: props.biName ?? '',
            ctaType: 'primary page dropdown',
            additionalInfo: props.biAdditionalInfo,
          }),
        );
      }}
      actionItem={{
        prefixIcon: <Add />,
        label: t('cairo.page.primary.cta'),
        dataHook: 'primary-actions',
        ...props,
        subItems: subItemsGrouped?.map((subItems) =>
          subItems?.map((subItem) => ({
            ...subItem,
            onClick: () => {
              reportBi(
                cairoPageCtaClicked({
                  location: 'Collection Page Header',
                  pageType: 'Collection',
                  ctaName: subItem.biName ?? '',
                  ctaType: 'primary page option',
                  additionalInfo: subItem.biAdditionalInfo,
                }),
              );
              subItem.onClick?.();
            },
          })),
        ),
        onClick: () => {
          reportBi(
            cairoPageCtaClicked({
              location: 'Collection Page Header',
              pageType: 'Collection',
              ctaName: props.biName ?? '',
              ctaType: 'primary page button',
              additionalInfo: props.biAdditionalInfo,
            }),
          );
          props.onClick?.();
        },
      }}
    />
  );
}
