/* eslint-disable jsx-a11y/anchor-is-valid */
import React, { FunctionComponent, useState } from 'react';
import cn from 'classnames';

import { StyledDivCounter, StyledAnchor } from '../../StyledComponents';
import { useTheme } from '../../Theme';
import { SideBarAccordGroupProps, SideBarAccordItemProps } from '../types.d';

const SideBarAccordItem: FunctionComponent<SideBarAccordItemProps> = ({
  className = '',
  color,
  count,
  isSelected,
  minimized = false,
  onClick = () => {},
  text,
}) => {
  const theme = useTheme();
  const classNames = cn({
    active: isSelected,
    sidebar1__link: true,
    [className]: true,
  });
  return (
    <StyledAnchor className={classNames} onClick={onClick} role="presentation" key={text} $theme={theme} $selected={isSelected}>
      {color ? <div className="sidebar1__status" style={{ backgroundColor: color }} /> : null}
      {!minimized && (
        <>
          {text}
          <StyledDivCounter $theme={theme} className="sidebar1__counter">
            {count}
          </StyledDivCounter>
        </>
      )}
    </StyledAnchor>
  );
};

export const SideBarAccordGroup: FunctionComponent<SideBarAccordGroupProps> = ({
  className = '',
  customElements = <></>,
  items,
  minimized = false,
  onClick = () => {},
  position = 'top',
  title,
}): React.ReactElement => {
  const [isActive, setIsActive] = useState(false);

  const classNames = cn({
    sidebar__group: true,
    'js-accord-item': true,
    active: isActive,
    bottom: position === 'bottom',
    [className]: true,
  });

  const innerClassNames = cn({
    sidebar__inner: true,
    'js-accord-body': true,
    active: isActive,
  });

  const toggleActive = () => {
    setIsActive((prevState) => !prevState);
  };
  const handleOnClick = () => {
    toggleActive();
    onClick();
  };

  return (
    <div className={classNames}>
      <div className="sidebar__category js-accord-head" onClick={handleOnClick} role="presentation">
        {minimized ? '' : title}
      </div>
      <div className={innerClassNames}>
        {items.map((i) => SideBarAccordItem({ ...i, minimized }))}
        {customElements}
      </div>
    </div>
  );
};
