import { useContext, useEffect, useRef, useState } from 'react';
import CustomInstructions from '../../components/CustomInstructions/CustomInstructions';
import Input from '../../components/Input/input';
import VisibleOnPages from '../../components/VisibleOnPages';
import { PremiumSettings } from '../../types/types';
import { useNavigate } from 'react-router-dom';
import { PremiumSettingsContext } from '../../context/contexts';
import Loading from '../../components/Loading';
import NoPoweredBy from '../../components/NoPoweredBy';

export default function PremiumFeatures() {
  const [mainGoal, setMainGoal] = useState<string>('');
  const [customInstructions, setCustomInstructions] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);
  const oldMainGoal = useRef(mainGoal);
  const navigate = useNavigate();
  const premiumSettings = useContext(PremiumSettingsContext);

  useEffect(() => {
    if (premiumSettings) {
      setLoading(false);
      setPremiumSettings(premiumSettings);
    }
  }, [premiumSettings]);

  function setPremiumSettings(premiumSettings: PremiumSettings): void {
    // Set the main goal if it is set
    if (premiumSettings.mainGoal) {
      setMainGoal(premiumSettings.mainGoal);
      oldMainGoal.current = premiumSettings.mainGoal;
    } else {
      const mainGoal =
        'your goal is to help users to find things on this website.';
      setMainGoal(mainGoal);
      oldMainGoal.current = mainGoal;
    }

    // Set the custom instructions if they are set
    if (premiumSettings.customInstructions) {
      setCustomInstructions(premiumSettings.customInstructions);
    } else {
      setCustomInstructions([
        'Use the ai search index "botfoundry-data-index" to find information about the site.',
        'Do not provide answers unrelated to questions about the website. If a user asks a question that is not related to the website, you can respond that you can only help with questions about the current website.',
        'If you cant find a good answer to a question, you can respond that you are not sure and ask the user reframe the question.',
      ]);
    }
  }

  async function postMainGoal(value: string): Promise<void> {
    try {
      const response = await fetch(
        `${wpApiSettings.root}botfoundry/v1/set-main-goal`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-WP-Nonce': wpApiSettings.nonce, // Include the nonce for authentication
          },
          body: JSON.stringify({ mainGoal: value }),
        },
      );
      if (!response.ok) {
        throw new Error('Failed to post main goal');
      }
    } catch (error) {
      console.error(error);
    }

    setMainGoal(value);
    oldMainGoal.current = value;
  }

  if (loading) {
    return <Loading />;
  }
  return (
    <>
      {!premiumSettings.active ? (
        <div className="premium-features mb-24">
          <h4>Upgrade to premium to unlock these features</h4>
          <p>
            With premium you can set the main goal for the chat bot, add custom
            instructions and set the chat bot to only be visible on certain
            pages.
          </p>
          <button
            onClick={() => {
              navigate('/activate-premium');
            }}
            className="botfoundry-btn std-button"
          >
            Upgrade to premium
          </button>
        </div>
      ) : null}

      <div
        className={
          premiumSettings.active
            ? 'premium-features'
            : 'premium-features disabled'
        }
      >
        <div className="d-flex flex-column gap-24">
          <div>
            <h4 className="mt-0 mb-8">Chat bot main goal</h4>
            <p>
              Here you can set the main goal for the chat bot. This is the main
              purpose of the chat bot and should be a short sentence that
              describes the main goal of the chat bot.
            </p>
            <Input
              value={mainGoal}
              onChange={(value) => {
                setMainGoal(value);
              }}
              className="large-input mb-16"
              disabled={!premiumSettings.active}
            />
            <button
              className="botfoundry-btn std-button"
              onClick={() => postMainGoal(mainGoal)}
            >
              Save
            </button>
          </div>
          <hr />
          <div>
            <CustomInstructions
              customInstructions={customInstructions}
              setCustomInstructions={setCustomInstructions}
            />
          </div>
          <hr />
          <div>
            <VisibleOnPages />
          </div>
          <hr />
          <div>
            <NoPoweredBy />
          </div>
        </div>
      </div>
    </>
  );
}
