'use client';

import * as React from 'react';
import { Icon24ChevronDown, Icon24ChevronUp } from '@vkontakte/icons';
import { callMultiple } from '../../lib/callMultiple';
import { SimpleCell, type SimpleCellProps } from '../SimpleCell/SimpleCell';
import { AccordionContext } from './AccordionContext';
import { AccordionIcon } from './AccordionIcon';

export interface AccordionSummaryProps extends Omit<SimpleCellProps, 'chevron'> {
  /**
   * Иконка для раскрытия контента.
   */
  ExpandIcon?: React.ElementType | undefined;
  /**
   * Иконка для сворачивания контента.
   */
  CollapseIcon?: React.ElementType | undefined;
  /**
   * Позиция иконки.
   */
  iconPosition?: 'before' | 'after' | 'none' | undefined;
}

export const AccordionSummary = ({
  after,
  before,
  ExpandIcon = Icon24ChevronDown,
  CollapseIcon = Icon24ChevronUp,
  iconPosition = 'after',
  onClick,
  children,
  ...restProps
}: AccordionSummaryProps) => {
  const { expanded, labelId, contentId, onChange } = React.useContext(AccordionContext);

  const icon = (
    // Обертка нужна для правильной работы с отступами в SimpleCell
    <AccordionIcon CollapseIcon={CollapseIcon} ExpandIcon={ExpandIcon} />
  );

  const toggle = () => onChange(!expanded);

  return (
    <SimpleCell
      id={labelId}
      aria-expanded={expanded}
      aria-controls={contentId}
      onClick={callMultiple(toggle, onClick)}
      before={
        <>
          {iconPosition === 'before' && icon}
          {before}
        </>
      }
      after={
        <>
          {after}
          {iconPosition === 'after' && icon}
        </>
      }
      {...restProps}
    >
      {children}
    </SimpleCell>
  );
};
