import { useContext, useEffect, useState } from 'react';
import Input from '../../components/Input/input';
import Loading from '../../components/Loading';
import Modal from '../../components/Modal';
import Checkout from './checkout';
import {
  AdminSettingsDispatchContext,
  PremiumSettingsContext,
  PremiumSettingsDispatchContext,
} from '../../context/contexts';
import { useNavigate } from 'react-router-dom';
import { fetchPremiumSettings } from '../../utils/useGetPremiumSettings';

export default function ActivatePremium() {
  const [value, setValue] = useState('');
  const [loading, setLoading] = useState(false);
  const [modalOpen, setModalOpen] = useState(false);
  const [error, setError] = useState('');
  const premiumSettings = useContext(PremiumSettingsContext);
  const premiumSettingsDispatchContext = useContext(
    PremiumSettingsDispatchContext,
  );

  const adminSettingsDispatch = useContext(AdminSettingsDispatchContext);
  const navigate = useNavigate();

  useEffect(() => {
    // Add the Stripe script
    const script = document.createElement('script');
    script.src = 'https://js.stripe.com/v3/';
    document.head.appendChild(script);
    if (premiumSettings) {
      setLoading(false);
    }
  }, [premiumSettings]);

  /**
   * Send a message to the chatbot
   */
  async function sendSerial(serial: string) {
    if (!serial) return alert('Please enter a serial number');
    setLoading(true);
    setModalOpen(true);
    try {
      const body = {
        serial: serial,
        env: process.env.NODE_ENV,
      };
      const request = await fetch(
        `${wpApiSettings.root}botfoundry/v1/activate-premium`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-WP-Nonce': wpApiSettings.nonce,
          },
          body: JSON.stringify(body),
        },
      );

      const msg = await request.json();
      if (!request.ok) {
        setLoading(false);
        if (msg) {
          setError('Error:' + msg);
        } else {
          setError('Error: an error occurred while activating premium');
        }
      } else {
        setLoading(false);
        adminSettingsDispatch({
          type: 'SET_ADMIN_SETTINGS_LOADING',
          payload: true,
        });
        const premiumSettings = await fetchPremiumSettings();
        if (premiumSettings?.active) {
          premiumSettingsDispatchContext({
            type: 'SET_PREMIUM_SETTINGS',
            payload: premiumSettings,
          });
          navigate('/premium-settings');
          adminSettingsDispatch({
            type: 'SET_ADMIN_SETTINGS_LOADING',
            payload: false,
          });
        }
      }
    } catch (error) {
      console.log('Error:', error);
      setError('Error: an error occurred while activating premium.');
    }
  }

  return (
    <div className="d-flex flex-column gap-16 h-100">
      <p>
        To activate premium features, please enter the serial number you
        received when you purchased the premium version of{' '}
        {process.env.PLUGIN_NAME}.
      </p>
      {!premiumSettings.active ? (
        <>
          <Checkout active={premiumSettings.active} />
          <Modal
            open={modalOpen}
            title={'Activating Premium'}
            content={
              error ? (
                <div>{error}</div>
              ) : (
                loading && (
                  <div className="d-flex">
                    <Loading style={{ margin: 'auto', marginTop: 24 }} />
                  </div>
                )
              )
            }
            width={150}
            button={!loading ? 'Close' : ''}
            onClose={() => setModalOpen(false)}
          />
          <div className="divider" />
          <div className="premium-features">
            <h1>Premium Features</h1>
            <ul className="premium-list">
              <li>
                <strong>Unlimited Chat Interactions:</strong> Experience
                uninterrupted conversations with our chatbot—even during peak
                usage, your service remains seamless.
              </li>
              <li>
                <strong>Advanced Customization:</strong> Fully tailor the
                chatbot’s responses by providing personalized instructions that
                align with your specific needs.
              </li>
              <li>
                <strong>Selective Page Integration:</strong> Easily enable the
                chat feature on targeted pages, ensuring focused support exactly
                where it’s needed.
              </li>
              <li>
                <strong>More advanced models:</strong> When available you get
                acess to more advanced models.
              </li>
            </ul>
          </div>
          <Input
            className="large-input"
            label="Serial"
            value={value}
            onChange={(value) => setValue(value)}
          />
          <div>
            <button
              className="botfoundry-btn std-button"
              onClick={() => sendSerial(value)}
            >
              Activate
            </button>
          </div>
        </>
      ) : (
        <>
          <Input
            className="large-input"
            label="Serial"
            value={value}
            onChange={(value) => setValue(value)}
          />
          <div>
            <button
              className="botfoundry-btn std-button"
              onClick={() => sendSerial(value)}
            >
              Activate
            </button>
          </div>
        </>
      )}
    </div>
  );
}
