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

export default function PremiumSettingsPage() {
  const [value, setValue] = useState('');
  const adminSettings = useContext(AdminSettingsContext);
  const [loading, setLoading] = useState(false);
  const [modalOpen, setModalOpen] = useState(false);
  const [error, setError] = useState('');
  const premiumSettingsDispatchContext = useContext(
    PremiumSettingsDispatchContext,
  );
  const adminSettingsDispatch = useContext(AdminSettingsDispatchContext);
  const navigate = useNavigate();

  useEffect(() => {
    // Add the Stripe script
    const script = document.createElement('script');
    script.src = process.env.EXTERNAL_URL + '/static/stripe/client.js';
    document.head.appendChild(script);
    script.onload = () => {
      setLoading(false);
    };
  }, []);

  /**
   * 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.');
    }
  }

  if (loading) {
    return null;
  }
  return (
    <div className="d-flex flex-column stripe-success gap-32">
      <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)}
      />
      <section>
        <div className="product Box-root">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            xmlnsXlink="http://www.w3.org/1999/xlink"
            width="14px"
            height="16px"
            viewBox="0 0 14 16"
            version="1.1"
          >
            <defs />
            <g
              id="Flow"
              stroke="none"
              stroke-width="1"
              fill="none"
              fill-rule="evenodd"
            >
              <g
                id="0-Default"
                transform="translate(-121.000000, -40.000000)"
                fill="#E184DF"
              >
                <path
                  d="M127,50 L126,50 C123.238576,50 121,47.7614237 121,45 C121,42.2385763 123.238576,40 126,40 L135,40 L135,56 L133,56 L133,42 L129,42 L129,56 L127,56 L127,50 Z M127,48 L127,42 L126,42 C124.343146,42 123,43.3431458 123,45 C123,46.6568542 124.343146,48 126,48 L127,48 Z"
                  id="Pilcrow"
                />
              </g>
            </g>
          </svg>
          <div className="description Box-root">
            <h3>
              Subscription to Starter plan successful! Check you email for your
              serial code.
            </h3>
          </div>
        </div>
        <form
          action={
            process.env.EXTERNAL_URL + '/api/stripe/create-portal-session'
          }
          method="POST"
        >
          <input
            type="hidden"
            id="site-id"
            name="site_id"
            value={adminSettings.site_id}
          />
          <button id="checkout-and-portal-button" type="submit">
            Manage your billing information
          </button>
        </form>
      </section>
      <div className="d-flex flex-column gap-16 h-100">
        <Input
          className="large-input"
          label="Serial"
          value={value}
          onChange={(value) => setValue(value)}
        />
        <div>
          <button
            className="botfoundry-btn std-button"
            onClick={() => sendSerial(value)}
          >
            Reactivate Premium
          </button>
        </div>
      </div>
    </div>
  );
}
