import { useEffect, useState } from '@wordpress/element';
import apiFetch from '@wordpress/api-fetch';
import { TextControl, ToolbarDropdownMenu } from '@wordpress/components';
import { DropdownOption } from '@wordpress/components/build-types/dropdown-menu/types';

interface IconPickerProps {
  parentCallback: (inlineSvg: any) => void;
  initialIconCode: string;
}

interface IconData {
  icon_url: string;
  icons: string[];
}

function IconList({
  iconData,
  onActiveIcon,
}: {
  iconData: IconData;
  onActiveIcon: (icon: string) => void;
}) {
  const list: DropdownOption[] = [];

  if (iconData.icons == null) return [];
  // iterate over the icons and show img with icon based on icon_url and icon
  iconData.icons.forEach((icon) => {
    list.push({
      title: icon,
      icon: (
        <img
          className="blockbite--editor-icon"
          width="24px"
          height="24px"
          src={`${iconData.icon_url}/${icon}.svg`}
          onClick={() => onActiveIcon(icon)}
        />
      ),
      onClick: () => onActiveIcon(icon),
    });
  });

  return list;
}

export default function IconPicker({
  parentCallback,
  initialIconCode,
}: IconPickerProps) {
  const [iconData, setIconData] = useState({ icon_url: '', icons: [] });
  const [activeIcon, setActiveIcon] = useState('');
  const [activeKeyword, setActiveKeyword] = useState('');
  const [loadingIcons, setLoadingIcons] = useState(true);
  const filteredIconData = {
    icon_url: iconData.icon_url,
    icons: iconData.icons.filter((icon) =>
      icon.toLowerCase().includes(activeKeyword.toLowerCase())
    ),
  };

  useEffect(() => {
    apiFetch({ path: '/blockbite/v1/block-helpers/get-icons/' }).then(
      (iconData: IconData) => {
        setIconData({
          icon_url: iconData.icon_url,
          icons: iconData.icons.map((icon: string) => icon),
        });
        setLoadingIcons(false);
      }
    );
  }, []);

  const sendBackData = (inlineSvg: any) => {
    if (inlineSvg === undefined) return;
    parentCallback(inlineSvg);
  };

  // api call for icon without .svg
  useEffect(() => {
    if (activeIcon === '') return;
    setActiveKeyword('');
    apiFetch({
      path: '/blockbite/v1/block-helpers/pick-icon/' + activeIcon,
    }).then((inlineSvg) => {
      sendBackData(inlineSvg);
    });
  }, [activeIcon]);

  return (
    <ToolbarDropdownMenu
      icon={
        activeIcon ? (
          <img
            className="blockbite--editor-icon"
            width="24px"
            height="24px"
            src={`${iconData.icon_url}/${activeIcon}.svg`}
          />
        ) : (
          <img
            className="blockbite--editor-icon"
            width="24px"
            height="24px"
            src={`data:image/svg+xml;utf8,${encodeURIComponent(
              initialIconCode
            )}`}
          />
        )
      }
      label="Change icon"
      controls={IconList({
        iconData: filteredIconData,
        onActiveIcon: setActiveIcon,
      })}
      children={() => {
        return loadingIcons ? (
          <span>Loading icons…</span>
        ) : iconData.icons.length === 0 ? (
          <p>
            No icons found. Icons should be added to:
            <br />
            your_theme/resources/svg/
          </p>
        ) : (
          <div className="min-w-36 p-2">
            <TextControl
              label="Search icons"
              value={activeKeyword}
              placeholder="arrow-up"
              onChange={(value) => setActiveKeyword(value)}
            />
          </div>
        );
      }}
    />
  );
}
