import jss, { StyleSheet } from "jss";
import preset from "jss-preset-default";
import { FC, useEffect, useState } from "react";

import { BackdropInfo } from "@dndbeyond/character-rules-engine/es";

import { DDB_MEDIA_URL } from "../../../../../constants";

interface BackdropStylesProps {
  backdrop: BackdropInfo;
}

export const BackdropStyles: FC<BackdropStylesProps> = ({ backdrop }) => {
  const [sheet, setSheet] = useState<StyleSheet | null>(null);

  const renderStyleSheet = (): void => {
    if (backdrop.backdropAvatarUrl !== null) {
      let tempSheet = jss.createStyleSheet({});

      const bodyStyles = window.getComputedStyle(document.body);
      const newNavHeight = bodyStyles.getPropertyValue(
        "--top-navigation-height"
      );
      const navHeightVar = newNavHeight
        ? "--top-navigation-height"
        : "--ttui-site-nav-height";

      if (tempSheet !== null) {
        let breakpointRules: Record<string, string> = [
          { width: 768, image: backdrop.backdropAvatarUrl },
          { width: 1024, image: backdrop.backdropAvatarUrl },
          { width: 1200, image: backdrop.backdropAvatarUrl },
          {
            width: 1921,
            image:
              backdrop.smallBackdropAvatarUrl === null
                ? ""
                : backdrop.smallBackdropAvatarUrl,
          },
          {
            width: 2561,
            image:
              backdrop.largeBackdropAvatarUrl === null
                ? ""
                : backdrop.largeBackdropAvatarUrl,
          },
        ].reduce((acc, breakpoint) => {
          acc[`@media (min-width: ${breakpoint.width}px)`] = {
            background: `url(${breakpoint.image}) no-repeat center calc(var(${navHeightVar}) + var(--sheet-header-height)), url(${DDB_MEDIA_URL}/attachments/0/84/background_texture.png) #f9f9f9 !important`,
          };
          return acc;
        }, {});

        tempSheet.addRules({
          "@global": {
            "html body.body-rpgcharacter-sheet": breakpointRules,
          },
        });

        tempSheet.attach();
        setSheet(tempSheet);
      }
    }
  };

  const removeStyleSheet = (): void => {
    if (sheet) {
      jss.removeStyleSheet(sheet);
      setSheet(null);
    }
  };

  useEffect(() => {
    jss.setup(preset());
    renderStyleSheet();
    return () => {
      removeStyleSheet();
    };
  }, []);

  useEffect(() => {
    removeStyleSheet();
    renderStyleSheet();
  }, [backdrop]);

  return null;
};
