import { useContext, useEffect, useState } from 'react';
import { v4 } from 'uuid';
import TopBar from './components/TopBar';
import ContentPane from './pages/ContentPane';
import { Links, PremiumSettings } from './types/types';
import { useGetSettings } from './utils/functions';

import styles from './index.module.scss';
import Loading from './components/Loading';
import {
  AdminSettingsContext,
  AdminSettingsDispatchContext,
  PremiumSettingsContext,
} from './context/contexts';
import PremiumSettingsPage from './pages/PremiumSettings';
import useGetPremiumSettings from './utils/useGetPremiumSettings';

export default function InitSettingsPage() {
  const getSettings = useGetSettings();
  const getPremiumSettings = useGetPremiumSettings();
  const adminSettings = useContext(AdminSettingsContext);
  const adminSettingsDispatch = useContext(AdminSettingsDispatchContext);
  const premiumSettings = useContext(PremiumSettingsContext);
  const [error, setError] = useState('');
  const [links, setLinks] = useState<Links>([]);

  useEffect(() => {
    initialize();
  }, [wpApiSettings]);

  useEffect(() => {
    if (premiumSettings) {
      _setLinks(premiumSettings);
    }
  }, [premiumSettings]);

  function _setLinks(settings: PremiumSettings) {
    if (settings.active) {
      setLinks([
        { title: 'Setup', path: '/' },
        { title: 'Chat bot customizer', path: '/chat-bot-customizer' },
        { title: 'Premium features', path: '/premium-features' },
        {
          title: 'Premium settings',
          path: '/premium-settings',
          component: <PremiumSettingsPage />,
        },
      ]);
    } else {
      setLinks([
        { title: 'Setup', path: '/' },
        { title: 'Chat bot customizer', path: '/chat-bot-customizer' },
        { title: 'Premium features', path: '/premium-features' },
        { title: 'Activate premium', path: '/activate-premium' },
      ]);
    }
  }

  async function initialize() {
    if (!wpApiSettings) {
      setError('An error occurred while checking settings.');
      return;
    }

    const id = v4();

    // Endpoint should send in id but only store it if it does not exist
    const result = await fetch(`${wpApiSettings.root}botfoundry/v1/init`, {
      headers: {
        'X-WP-Nonce': wpApiSettings.nonce, // Include the nonce for authentication
        'Content-Type': 'application/json',
      },
      method: 'POST',
      body: JSON.stringify(id),
    });

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

      const json = (await result.json()) as { site_id: string };
      adminSettingsDispatch({
        type: 'SET_ADMIN_SETTINGS',
        payload: { ...adminSettings, site_id: json.site_id },
      });
      const settings = await getSettings(
        () => null,
        () => setError('An error occurred while fetching settings.')
      );

      if (settings) {
        const premiumSettings = await getPremiumSettings();
        if (premiumSettings) {
          adminSettingsDispatch({
            type: 'SET_ADMIN_SETTINGS_LOADING',
            payload: false,
          });
        }
      }
    } catch (error) {
      setError('An error occurred while fetching settings.');
      return;
    }
  }

  if (error) {
    return <div>{error}</div>;
  }
  if (adminSettings.loading) {
    return (
      <div className="botfoundry">
        <div
          className="d-flex justify-content-center h-100 w-100"
          style={{ marginTop: '30vh' }}
        >
          <Loading />
        </div>
      </div>
    );
  }
  return (
    <div className="botfoundry">
      <div className="d-flex justify-content-between align-items-center">
        <h1 className={styles['settings-title']}>BotFoundry</h1>
        <div className="text-muted mt-auto">version: alpha 0.0.1</div>
      </div>
      <div className={styles['botfoundry-wrapper']}>
        <TopBar links={links} />
        <ContentPane links={links} />
      </div>
    </div>
  );
}
