import React, { ReactNode, useEffect } from 'react';
import { configClass, varsClass } from 'folds';
import {
  DarkTheme,
  LightTheme,
  LotusTerminalLightTheme,
  LotusTerminalTheme,
  ThemeContextProvider,
  ThemeKind,
  useActiveTheme,
  useSystemThemeKind,
} from '../hooks/useTheme';
import { lotusTerminalBodyClass } from '../../lotus-terminal.css';
import { useSetting } from '../state/hooks/settings';
import { settingsAtom } from '../state/settings';
import { runLotusBootSequence } from '../../lotus-boot';

export function UnAuthRouteThemeManager() {
  const systemThemeKind = useSystemThemeKind();
  const [lotusTerminal] = useSetting(settingsAtom, 'lotusTerminal');

  useEffect(() => {
    document.body.className = '';
    document.body.classList.add(configClass, varsClass);
    if (lotusTerminal) {
      const isLight = systemThemeKind === ThemeKind.Light;
      document.documentElement.setAttribute('data-theme', isLight ? 'light' : 'dark');
      document.body.classList.add(
        ...(isLight ? LotusTerminalLightTheme : LotusTerminalTheme).classNames,
      );
      document.body.classList.add(lotusTerminalBodyClass);
    } else {
      document.documentElement.removeAttribute('data-theme');
      if (systemThemeKind === ThemeKind.Dark) {
        document.body.classList.add(...DarkTheme.classNames);
      } else {
        document.body.classList.add(...LightTheme.classNames);
      }
    }
  }, [systemThemeKind, lotusTerminal]);

  return null;
}

export function AuthRouteThemeManager({ children }: { children: ReactNode }) {
  const activeTheme = useActiveTheme();
  const [monochromeMode] = useSetting(settingsAtom, 'monochromeMode');
  const [lotusTerminal] = useSetting(settingsAtom, 'lotusTerminal');

  const terminalIsLight = lotusTerminal && activeTheme.kind === ThemeKind.Light;
  const effectiveTheme = lotusTerminal
    ? terminalIsLight
      ? LotusTerminalLightTheme
      : LotusTerminalTheme
    : activeTheme;

  // Boot animation only fires when lotusTerminal is toggled on, not on every theme change
  useEffect(() => {
    if (lotusTerminal) runLotusBootSequence();
  }, [lotusTerminal]);

  useEffect(() => {
    document.body.className = '';
    document.body.classList.add(configClass, varsClass);
    document.body.classList.add(...effectiveTheme.classNames);
    if (lotusTerminal) {
      document.documentElement.setAttribute('data-theme', terminalIsLight ? 'light' : 'dark');
      document.body.classList.add(lotusTerminalBodyClass);
    } else {
      document.documentElement.removeAttribute('data-theme');
    }
    if (monochromeMode && !lotusTerminal) {
      document.body.style.filter = 'grayscale(1)';
    } else {
      document.body.style.filter = '';
    }
  }, [effectiveTheme, monochromeMode, lotusTerminal, terminalIsLight]);

  return <ThemeContextProvider value={effectiveTheme}>{children}</ThemeContextProvider>;
}
