import * as React from "react";
import { IconSelectorProps } from "./types";
import Icon, { IconTypes } from "@sc/plugins/webcomponents/v2/Icon";
import style from "./style";
import styled from "styled-components";
// use react-window https://react-window.now.sh/

const allIcons = Object.keys(IconTypes)
  // .slice(0, 30) // remove this to search the entire list
  .filter(
    (itm) =>
      itm.indexOf("Outlined") === -1 &&
      itm.indexOf("Rounded") === -1 &&
      itm.indexOf("Sharp") === -1 &&
      itm.indexOf("TwoTone") === -1
  );

export const treat = (str) =>
  str.replace(/^[a-z]|[A-Z]/g, (v, i) =>
    i === 0 ? v.toUpperCase() : " " + v.toLowerCase()
  );

/**
 * Shows a list of icons that the user can select from.
 *
 * Includes tools to help them search and filter
 */
const IconSelector: React.FC<IconSelectorProps> = ({
  onChange,
  containerStyle,
  isExpanded = true,
}) => {
  const [searchString, setSearchString] = React.useState<string>("");
  const [activeIcon, setActiveIcon] = React.useState<string>("");

  const icons = allIcons
    // .slice(0, 30) // remove this to search the entire list
    .filter(
      (itm) =>
        itm.toUpperCase().indexOf(searchString.toUpperCase()) > -1 ||
        itm.toUpperCase().indexOf(treat(searchString).toUpperCase()) > -1
    );

  const LI = styled.li`
    &:hover {
      background-color: #eee;
      border: 2px solid #0000cc;
    }
  `;

  return (
    <>
      <div>
        <input
          type="text"
          value={searchString}
          onChange={(e) => setSearchString(e.target.value)}
          placeholder="Search for an icon..."
          style={style.input}
          data-testid="Properties-IconSelector-input"
        />
      </div>
      {isExpanded || searchString.length ? (
        <ul
          style={{ ...style.UL, ...containerStyle }}
          data-testid="Properties-IconSelector"
        >
          {icons.map((icon, key) => (
            <LI
              key={key}
              style={{
                ...style.LI,
                ...(icon === IconTypes[activeIcon] && style.activeLI),
              }}
              onClick={() => {
                setActiveIcon(IconTypes[icon]);
                onChange(IconTypes[icon]);
              }}
              data-testid="Properties-IconSelector-icon"
            >
              <Icon type={IconTypes[icon]} style={style.iconStyle} />
              <p>{treat(icon)}</p>
            </LI>
          ))}
        </ul>
      ) : null}
    </>
  );
};

export default IconSelector;
