import { TextInput, SwitchItem } from '@vizality/components/settings';
import React, { memo, useEffect } from 'react';
import { useFilter } from '@vizality/hooks';
import { Messages } from '@vizality/i18n';

/**
 * Commands settings options.
 * @component
 * @returns {React.MemoExoticComponent<function(): React.ReactElement>}
 */
export default memo(({ builtin, search = '' }) => {
  const [ commandPrefix, setCommandPrefix ] = vizality.api.settings.useSetting('commandPrefix', '.');
  const [ replaceClyde, setReplaceClyde ] = vizality.api.settings.useSetting('replaceClyde', true);

  const items = [
    {
      search: [
        Messages.VIZALITY_COMMAND_PREFIX
      ],
      render: query =>
        <TextInput
          defaultValue={commandPrefix}
          onChange={p => {
            try {
              setCommandPrefix(!p ? '.' : p.replace(/\s+(?=\S)|(?<=\s)\s+/g, '').toLowerCase());
            } catch (err) {
              builtin.error(err);
            }
          }}
          onBlur={({ target }) => target.value = commandPrefix}
          error={commandPrefix === '/' ? 'Prefix should not be set to `/` as it is already in use by Discord and may disable Vizality autocompletions.' : ''}
        >
          {Messages.VIZALITY_COMMAND_PREFIX}
        </TextInput>
    },
    {
      search: [
        Messages.VIZALITY_SETTINGS_NO_CLYDE,
        Messages.VIZALITY_SETTINGS_NO_CLYDE_DESC.format({
          discordiaUrl: 'https://discordia.me/clyde',
          apiUrl: `${window.location.origin}/vizality/docs`
        })
      ],
      render: query =>
        <SwitchItem
          description={Messages.VIZALITY_SETTINGS_NO_CLYDE_DESC.format({
            discordiaUrl: 'https://discordia.me/clyde',
            apiUrl: `${window.location.origin}/vizality/docs`
          })}
          value={replaceClyde}
          onChange={() => {
            try {
              setReplaceClyde(!replaceClyde);
            } catch (err) {
              builtin.error(err);
            }
          }}
        >
          {Messages.VIZALITY_SETTINGS_NO_CLYDE}
        </SwitchItem>
    }
  ];

  const [ query, setQuery, filteredResults ] = useFilter({
    keys: [ 'search' ],
    data: items
  });

  useEffect(() => {
    setQuery(search);
  }, [ search ]);

  return filteredResults.map(result => result.render(query));
});
