/**
 * External dependencies
 */
import clsx from "clsx";
import styled from "@emotion/styled";

/**
 * WordPress dependencies
 */
import { Icon, chevronDown } from "@wordpress/icons";
import { BaseControl } from "@wordpress/components";

/**
 * Internal dependencies
 */

const GroupItemToggleStyled = styled.div`
  display: flex;
  align-items: center;
  margin-bottom: 0 !important;

  &.is-toggle-title {
    cursor: pointer;
  }

  .components-base-control__label {
    margin: 0;

    code {
      text-transform: none;
    }
  }

  .icon {
    margin-left: auto;
    line-height: 1;
  }

  &.is-opened {
    svg {
      transform: rotate(180deg);
    }
  }

  &.is-closed ~ * {
    display: none;
  }
`;

export const GroupItemToggle = ({
  isOpen,
  setIsOpen,
  label,
  className,
  isToggleTitle = false,
}) => {
  if (!label) {
    return null;
  }

  const clickProps = { onClick: () => setIsOpen(!isOpen), tabIndex: 0 };

  return (
    <GroupItemToggleStyled
      className={clsx("group-item-toggle", className, {
        "is-opened": isOpen,
        "is-closed": !isOpen,
        "is-toggle-title": isToggleTitle,
      })}
      {...(isToggleTitle ? clickProps : {})}
    >
      <BaseControl.VisualLabel>{label}</BaseControl.VisualLabel>
      <a className="icon" href="#" {...(!isToggleTitle ? clickProps : {})}>
        <Icon icon={chevronDown} />
      </a>
    </GroupItemToggleStyled>
  );
};
