import React from "react";
import PropTypes from "prop-types";
import { Box, Flex, Typography } from "@strapi/design-system";
import { FEATURE_GROUPS, FEATURE_REGISTRY, featureIconMarkup } from "../../../registry/features";

const iconStyle = {
  display: "inline-flex",
  alignItems: "center",
  justifyContent: "center",
  width: 16,
  height: 16,
  flex: "0 0 auto",
  opacity: 0.8,
};

const FeaturesTab = ({ features, onChange }) => {
  const toggleFeature = (name, checked) => {
    if (checked) {
      onChange([...features, name]);
      return;
    }
    onChange(features.filter((feature) => feature !== name));
  };

  return (
    <Flex direction="column" alignItems="stretch" gap={4}>
      {FEATURE_GROUPS.map((group) => {
        const groupFeatures = Object.entries(FEATURE_REGISTRY).filter(
          ([, meta]) => meta.group === group.id
        );

        return (
          <Box key={group.id}>
            <Typography variant="sigma" textColor="neutral600">
              {group.label}
            </Typography>
            <Flex wrap="wrap" gap={3} paddingTop={2}>
              {groupFeatures.map(([name, meta]) => (
                <label
                  key={name}
                  title={meta.description}
                  style={{ display: "flex", alignItems: "center", gap: 6, minWidth: 220, cursor: "pointer" }}
                >
                  <input
                    type="checkbox"
                    checked={features.includes(name)}
                    onChange={(event) => toggleFeature(name, event.target.checked)}
                  />
                  <span
                    style={iconStyle}
                    aria-hidden="true"
                    dangerouslySetInnerHTML={{ __html: featureIconMarkup(meta.icon) }}
                  />
                  <Typography>
                    {name}
                    {meta.requires?.length ? (
                      <Typography variant="pi" textColor="neutral500">
                        {" "}
                        (needs {meta.requires.join(", ")})
                      </Typography>
                    ) : null}
                  </Typography>
                </label>
              ))}
            </Flex>
          </Box>
        );
      })}
    </Flex>
  );
};

FeaturesTab.propTypes = {
  features: PropTypes.array.isRequired,
  onChange: PropTypes.func.isRequired,
};

export default FeaturesTab;
