import { useContext } from 'react';
import Switch from '../../components/Switch';
import {
  SettingsContext,
  SettingsDispatchContext,
} from '../../context/contexts';

export default function OnOff() {
  const settings = useContext(SettingsContext);
  const dispatch = useContext(SettingsDispatchContext);

  async function callBack() {
    try {
      const result = await fetch(
        `${wpApiSettings.root}botfoundry/v1/set-ai-enabled`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-WP-Nonce': wpApiSettings.nonce,
          },
          body: JSON.stringify({
            aiEnabled: !settings.aiEnabled,
          }),
        }
      );

      if (!result.ok) {
        throw new Error('An error occurred while fetching settings.');
      }

      dispatch({
        type: 'TOGGLE_AI',
      });
    } catch (error) {
      console.error(error);
    }
  }
  return (
    <>
      <p>
        Click the button below to enable the AI you selected for your chatbot.
      </p>
      <Switch enabled={settings.aiEnabled} callBack={callBack} />
    </>
  );
}
