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

export default memo(({ builtin, search = '' }) => {
  const [ reactDeveloperTools, setReactDeveloperTools ] = vizality.api.settings.useSetting('reactDeveloperTools', false);
  const [ fluxDispatcherLogs, setFluxDispatcherLogs ] = vizality.api.settings.useSetting('fluxDispatcherLogs', false);
  const [ hotReload, setHotReload ] = vizality.api.settings.useSetting('hotReload', false);

  const items = [
    {
      search: [
        Messages.VIZALITY_SETTINGS_REACT_DEVELOPER_TOOLS,
        Messages.VIZALITY_SETTINGS_REACT_DEVELOPER_TOOLS_DESC
      ],
      render: query =>
        <SwitchItem
          description={Messages.VIZALITY_SETTINGS_REACT_DEVELOPER_TOOLS_DESC}
          value={reactDeveloperTools}
          onChange={() => {
            try {
              setReactDeveloperTools(!reactDeveloperTools);
            } catch (err) {
              builtin.error(err);
            }
          }}
          info={Messages.VIZALITY_SETTINGS_REACT_DEVELOPER_TOOLS_WARNING}
          requiresRestart
        >
          {Messages.VIZALITY_SETTINGS_REACT_DEVELOPER_TOOLS}
        </SwitchItem>
    },
    {
      search: [
        Messages.VIZALITY_SETTINGS_LOG_FLUX_DISPATCHER_PAYLOADS,
        Messages.VIZALITY_SETTINGS_LOG_FLUX_DISPATCHER_PAYLOADS_DESC
      ],
      render: query =>
        <SwitchItem
          description={Messages.VIZALITY_SETTINGS_LOG_FLUX_DISPATCHER_PAYLOADS_DESC}
          value={fluxDispatcherLogs}
          onChange={() => {
            try {
              setFluxDispatcherLogs(!fluxDispatcherLogs);
            } catch (err) {
              builtin.error(err);
            }
          }}
          info={Messages.VIZALITY_SETTINGS_LOG_FLUX_DISPATCHER_PAYLOADS_INFO}
        >
          {Messages.VIZALITY_SETTINGS_LOG_FLUX_DISPATCHER_PAYLOADS}
        </SwitchItem>
    },
    {
      search: [
        Messages.VIZALITY_SETTINGS_PLUGIN_HOT_RELOAD,
        Messages.VIZALITY_SETTINGS_PLUGIN_HOT_RELOAD_DESC
      ],
      render: query =>
        <SwitchItem
          description={Messages.VIZALITY_SETTINGS_PLUGIN_HOT_RELOAD_DESC}
          value={hotReload}
          onChange={async () => {
            try {
              setHotReload(!hotReload);
              await vizality.manager.plugins.remountAll();
            } catch (err) {
              builtin.error(err);
            }
          }}
        >
          {Messages.VIZALITY_SETTINGS_PLUGIN_HOT_RELOAD}
        </SwitchItem>
    }
  ];

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

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