import { Box, IconButton, TextButton } from '@wix/design-system';
import React from 'react';
import { Section } from './CollectionSectionHeader.types';
import { useToolbarCollectionContext } from '../ToolbarCollectionContext';
import { withoutDefaults } from '@wix/bex-core';
import {
  wixPatternsSectionHeaderPrimaryActionClicked,
  cairoSectionCtaClicked,
} from '@wix/bex-core/bi';
import { ChevronDown, ChevronUp } from '@wix/wix-ui-icons-common';

export interface CollectionSectionHeaderActionBarProps {
  sectionId: string;
  sectionIndex: number;
  section: Section & { collapsed?: boolean };
  biComponentType: string;
  collapsible?: boolean;
  onToggleCollapse?: (sectionId: string) => void;
}

export const CollectionSectionHeaderActionBar = ({
  sectionId,
  sectionIndex,
  section,
  biComponentType,
  collapsible,
  onToggleCollapse,
}: CollectionSectionHeaderActionBarProps) => {
  const { toolbarBIReporter } = useToolbarCollectionContext();
  const { primaryAction, collapsed } = section;

  const handlePrimaryActionClick = () => {
    toolbarBIReporter.reportBi(
      wixPatternsSectionHeaderPrimaryActionClicked({
        sectionId,
        cta: primaryAction?.id,
        componentType: biComponentType,
      }),
    );
    primaryAction?.onClick?.();
  };

  const handleCollapseActionClick = () => {
    toolbarBIReporter.reportBi(
      withoutDefaults(cairoSectionCtaClicked)({
        location: 'Section Toolbar',
        sectionType: 'table',
        ctaName: collapsed ? 'expand' : 'collapse',
        sectionIndex,
      } as {}),
    );
    onToggleCollapse?.(sectionId);
  };

  return (
    <Box direction="horizontal" gap="SP2" placeItems="center">
      {primaryAction && (
        <TextButton
          prefixIcon={primaryAction.prefixIcon}
          dataHook="collection-section-header-primary-action"
          onClick={handlePrimaryActionClick}
          size="small"
        >
          {primaryAction.label}
        </TextButton>
      )}
      {collapsible && (
        <IconButton
          size="tiny"
          dataHook="collection-section-header-collapse-action"
          skin="light"
          priority="primary"
          onClick={handleCollapseActionClick}
        >
          {collapsed ? <ChevronDown /> : <ChevronUp />}
        </IconButton>
      )}
    </Box>
  );
};
