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

/**
 * WordPress dependencies
 */
import { ToggleControl } from "@wordpress/components";
import { useState } from "@wordpress/element";

/**
 * Internal dependencies
 */
import { GroupItemToggle } from "../group-item-toggle";

const BlockSupportsStyled = styled.div`
  > .group-item-toggle {
    padding: 0;
    margin-bottom: 8px !important;
    border: 0;
  }

  > div {
    padding: 12px 12px 0;
    margin-bottom: 12px;
    border: 1px solid #ddd;
  }
`;

/**
 * Support features
 *
 * @param {*} param0
 * @returns
 */
const BlockSupports = ({
  label,
  features,
  premiumFeatures,
  name,
  value,
  onChange,
  isPremium,
}) => {
  const featureElements = Object.keys(features).map((featureName) => {
    const { [featureName]: featureValue } = value;
    return (
      <ToggleControl
        key={featureName}
        label={features[featureName]}
        checked={featureValue}
        onChange={onChange(name, value, featureName)}
        disabled={!isPremium && premiumFeatures.includes(featureName)}
      />
    );
  });

  const [isOpen, setIsOpen] = useState(
    () =>
      Object.keys(value)?.length &&
      Object.keys(value).some((feature) => !!value[feature]),
  );

  return (
    <BlockSupportsStyled>
      <GroupItemToggle
        isOpen={isOpen}
        setIsOpen={setIsOpen}
        label={label}
        isToggleTitle={true}
      />
      <div>{featureElements}</div>
    </BlockSupportsStyled>
  );
};

export default BlockSupports;
